当我尝试内联我的一个类的方法时遇到编译器错误。当我去掉“inline”关键字时,它就起作用了。
这是一个简化的例子:
main.cpp:
#include "my_class.h"
int main() {
MyClass c;
c.TestMethod();
return 0;
}
my_class.h:
class MyClass {
public:
void TestMethod();
};
my_class.cpp:
#include "my_class.h"
inline void MyClass::TestMethod() {
}
我尝试编译:
g++ main.cpp my_class.cpp
我得到错误:
main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'
如果我去掉“内联”,一切都很好。是什么导致了这个问题? (以及我应该如何内联类方法?有可能吗?)
谢谢。
最佳答案
内联函数的主体需要在 header 中,以便编译器可以在需要的地方实际替换它。见:How do you tell the compiler to make a member function inline?
关于C++内联类方法导致 undefined reference ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4769479/