C++内联类方法导致 undefined reference

标签 c++ inline

当我尝试内联我的一个类的方法时遇到编译器错误。当我去掉“inline”关键字时,它就起作用了。

这是一个简化的例子:

ma​​in.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/

相关文章:

C++ Google Test 将测试夹具构造函数定义放在哪里

c++ - Inline 是否将函数/方法限制在其当前源文件的范围内?

c - Gnu 作为后缀或操作数错误

c++ - 了解位运算及其效果

c++ - 在 C++ 中使用 "+"连接字符串

c++ - 在模板类中使用 vector 迭代器

c++ - 是否保证只有一个非内联内联函数的拷贝?

c++ - 如何处理可能是 std::string 或 std::wstring 的值

c++ - 更改任意数字类型值的范围刻度

CSS 内联 block 中心