C++内联类方法导致未定义的引用

Fra*_*kMN 46 c++ inline

当我尝试内联我的一个类的方法时,我收到编译器错误.当我拿走"内联"关键字时它会起作用.

这是一个简化的例子:

main.cpp中:

#include "my_class.h"

int main() {
  MyClass c;
  c.TestMethod();

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

my_class.h:

class MyClass {
 public:
  void TestMethod();
};
Run Code Online (Sandbox Code Playgroud)

my_class.cpp:

#include "my_class.h"

inline void MyClass::TestMethod() {
}
Run Code Online (Sandbox Code Playgroud)

我尝试编译:

g++ main.cpp my_class.cpp
Run Code Online (Sandbox Code Playgroud)

我收到错误:

main.cpp:(.text+0xd): undefined reference to `MyClass::TestMethod()'
Run Code Online (Sandbox Code Playgroud)

如果我带走"内联",一切都很好.是什么导致了这个问题?(我应该如何内联类方法?是否可能?)

谢谢.

cas*_*nca 40

内联函数的主体需要位于标题中,以便编译器实际上可以在需要的地方替换它.请参阅:如何告诉编译器使内联成员函数?


Ste*_*sop 17

7.1.2/4标准:

内联函数应在每个使用它的翻译单元中定义......

你在main.cpp中使用TestMethod,但它没有在那里定义.

......如果在一个翻译单元中内联声明具有外部链接的功能,则应在其出现的所有翻译单元中内联声明; 无需诊断.

您在my_class.cpp中定义(并因此也声明)TestMethod内联,但不在main.cpp中定义.

在这种情况下的修复是将函数定义移动到头文件,如下所示:

class MyClass {
 public:
  void TestMethod() {}
};
Run Code Online (Sandbox Code Playgroud)

或者像这样:

class MyClass {
 public:
  inline void TestMethod();
};

inline void MyClass::TestMethod() {}
Run Code Online (Sandbox Code Playgroud)