问题描述
类成员函数的声明不需要定义 inline
的函数,它只是函数的实际实现。例如,在头文件中:
The declaration of a class member function does not need to define a function as inline
, it is only the actual implementation of the function. For example, in the header file:
struct foo{
void bar(); // no need to define this as inline
}
在头文件中有一个类函数有?为什么我不能把内联函数的 .cpp
文件?如果我在哪里尝试把内联定义放在 .cpp
文件中,我会得到一个错误的行:
So why does the inline implementation of a classes function have to be in the header file? Why can't I put the inline function the .cpp
file? If I where to try to put the inline definition in the .cpp
file I would get an error along the lines of:
error LNK2019: unresolved external symbol
"public: void __thiscall foo::bar(void)"
(?bar@foo@@QAEXXZ) referenced in function _main
1>C:\Users\Me\Documents\Visual Studio 2012\Projects\inline\Debug\inline.exe
: fatal error LNK1120: 1 unresolved externals
推荐答案
inline
函数不必在头文件中,但由于内联函数的一个定义规则,函数的相同定义必须存在于使用它的每个翻译单元中。
The definition of an inline
function doesn't have to be in a header file but, because of the one definition rule for inline functions, an identical definition for the function must exist in every translation unit that uses it.
最简单的方法是将定义放在头文件中。
The easiest way to achieve this is by putting the definition in a header file.
如果你想把一个函数的定义放在一个单独的源文件中,那么你不应该声明它 inline
。未声明 inline
的函数并不意味着编译器不能内联函数。
If you want to put the definition of a function in a single source file then you shouldn't declare it inline
. A function not declared inline
does not mean that the compiler cannot inline the function.
是否应该声明函数 inline
或不是通常是一个选择,您应该根据一个定义规则的版本,最适合你的选择;添加 inline
,然后受后续约束的限制没有意义。
Whether you should declare a function inline
or not is usually a choice that you should make based on which version of the one definition rules it makes most sense for you to follow; adding inline
and then being restricted by the subsequent constraints makes little sense.
这篇关于为什么在头中有C ++内联函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!