对类方法的未定义引用

Undefined reference to class methods

本文关键字:引用 未定义 类方法      更新时间:2023-10-16

我有三个文件method.h、method.cpp、main.cpp

method.h

#ifndef METHOD_H
#define METHOD_H
class method {
public:
void printThisMethod();
private:
};
#endif

方法.cpp

#include "method.h"
inline void method::printThisMethod() {
//some methods done here
}

main.cpp

#include <iostream>
#include <string>
#include "method.h"
int main() {
method outputMethod;
outputMethod.printThisMethod;
}

我收到错误,

undefined reference to method::printThisMethod.

请帮忙,谢谢

删除inline关键字,或将定义移动到标头中(保留inline)。

inline用于放宽"一个定义规则"以允许在标头中进行定义。然而,也要求在每个使用它的翻译单元中都有一个定义,这通常要求定义在页眉中。

如果没有inline,则应用正常的链接规则,并且在一个翻译单元中必须有一个单独的定义。如果您从现有代码中删除inline,那么这就是您所拥有的。

(您还需要在函数调用outputMethod.printThisMethod()中添加括号,但据推测,您的真实代码中有括号,否则就不会出现链接错误。)

您需要更改

outputMethod.printThisMethod;

outputMethod.printThisMethod();