作者khoguan (Khoguan Phuann)
看板C_and_CPP
标题Re: [C++] 有关 inline 函式...
时间Sun Aug 21 15:33:07 2005
※ 引述《eliang ()》之铭言:
: 在 C++ Primer 这本书里, 提到 inline 函式应该定义在 header file 里
: 书上说明原因如下:
: An inline function may be defined more than once in a program as long as the
: definition appears only once in a given source file and the definition is
: exactly the same in each source file. By putting inline functions in headers,
: we ensure that the same definition is used whenever the function is called
: and that the compiler has the function definition available at the point of
: call.
: 我看不太懂它的意思...有没有人可以解释一下?
: 我之前都比较习惯把函式定义放在 .cpp 档, 函式宣告放 .h 档
: 因为这样程式码感觉起来比较乾净, 像是这样:
: // foo.h
: class foo {
: public:
: int f();
: };
: // foo.cpp
: inline int foo::f() {
: // short statement...
: }
既然要让它 inline, 就把函式定义一起写在 foo.h 中。
就是把你的 foo.cpp 档的内容直接copy到 foo.h 档原来的
内容後面。这样一样很乾净啦。
: 可是我发现这样写 "有时候" 编译会发生错误, 讯息大概就类似:
: [Linker error] undefined reference to 'foo::f()'
: 如果把 inline 去掉, 或照书上说的, 把定义改写到 .h 档, 就可以正常编译,
: 请问这是什麽原因? 谢谢!!
因为 inline 的本质就是可以让编译器在单独编译某个
使用到这个 inline function 的 source file的时候,
可以将整个 inline function 的定义插入并取代呼叫
inline function的那行叙述。你没给他函式定义,它
怎麽做这个动作呢?
当然,你指定要 inline 编译器不一定真能做到 inline,
inline 只是吾人对编译器的「建议」。但是好歹你要将
inline function 的定义透过 .h 档 include 进来,不然,
编译器根本没机会帮你 inline.
inline 的时机是定义简短的函式。太长的、或是 virtual
function 或是 recursive function 都不宜或不能 inline.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 220.130.208.168
1F:推 renderer:推 满重要的 inline 概念 61.228.217.108 08/21
2F:推 eliang:说明得很详细,感谢!! 210.58.40.9 08/21