C++ Qt Creator:“使用内联函数但从未定义”——为什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1421666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 19:54:49  来源:igfitidea点击:

Qt Creator: “inline function used but never defined” – why?

c++qtqt-creator

提问by Tony the Pony

Why am I getting this warning in Qt Creator: ` inline function ‘bool Lion::growl ()' used but never defined?

为什么我在 Qt Creator 中收到此警告:` inline function 'bool Lion::growl ()' used but never defined?

I double-checked my code, and have a declaration

我仔细检查了我的代码,并有一个声明

inline bool growl ()in Lion(lion.h)

inline bool growl ()Lion( lion.h)

and the corresponding implementation in lion.cpp:

以及相应的实现lion.cpp

inline bool Lion::growl ()

inline bool Lion::growl ()

What's going on?

这是怎么回事?

EDIT: My assumption has been that it is legal to define the actual inline method in the .cpp file (the inlinekeyword alerts the compiler to look for the method body elsewhere), or am I mistaken?

编辑:我的假设是在 .cpp 文件中定义实际的内联方法是合法的(inline关键字提醒编译器在别处寻找方法体),还是我错了?

I don't want to clutter my header files with implementation details.

我不想用实现细节来弄乱我的头文件。

回答by Johan

Well, I don't know the exact problem, but for starters:

好吧,我不知道确切的问题,但对于初学者来说:

  • Inline methods are supposed to be implemented in the header file. The compiler needs to know the code to actually inlineit.
  • Also using the "inline" keyword in the class declaration doesn't have any effect. But it cannot hurt either.
  • 内联方法应该在头文件中实现。编译器需要知道代码才能真正内联它。
  • 在类声明中使用“inline”关键字也没有任何效果。但它也不能伤害。

See also: c++ faq lite

另见:c++ faq lite

回答by Laurent Alebarde

Inline methods are supposed to be implemented in the header file. The compiler needs to know the code to actually inline it.

内联方法应该在头文件中实现。编译器需要知道代码才能真正内联它。

Except if the inline function is used in the same project, possibly in another file that #includeits header.

除非 inline 函数在同一个项目中使用,可能在另一个#include其标头的文件中使用。

I miss there is such a restriction for libraries because restricting headers to function prototypes make things more readable.

我想念对库有这样的限制,因为将头文件限制为函数原型会使事情更具可读性。

What about #include-ing the .cpp ?

怎么样的#include-ing在.cpp?

回答by 147

In addition to what Johan said, you cannot have a separate definition and declaration for the function even if both are in the same header file. This holds true especially for member functions of classes. The function code should be of the form:

除了 Johan 所说的之外,即使两者都在同一个头文件中,您也不能为该函数单独定义和声明。这尤其适用于类的成员函数。功能代码应采用以下形式:

class someClass
{
void someFunc()
{ ... }
}
// This will make the function inline even w/o the explicit 'inline'

And NOT of the form

而不是形式

class someClass
{
public:
     void someFunc();
}

void someClass::someFunc()
{ ... }