与类成员一起使用内联说明符时的未定义引用 [英] Undefined reference when inline specifier used with class member

查看:100
本文介绍了与类成员一起使用内联说明符时的未定义引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个类中有一些成员函数。当我使用内联说明符时,编译器会抱怨未定义引用。

I have some member functions in a class. When I use the inline specifier, the compiler complains of undefined reference.

我尝试过:

使用'

在类.cpp(其中指定了成员函数的函数)中,在函数声明之前使用 inline

Using 'inline' to precede the function declaration in the class .cpp (where the member functions are specified) file only.

同时执行上述两项操作。

Doing both of the above at the same time.

显然,其中一种方法是正确的做法,其他都不正确。但是尝试每个选项都不能使我得到一个已编译的程序。

Obviously, one of these ways is the correct thing to do, and the others are not correct. However trying each option did not get me a program which compiled.

这是我要执行的操作:

.hpp文件:

class A{
    void func();
}

.cpp文件:

...包括...

inline void A::func()
{ 
    ...
}

或者内联可能会出现在其他地方。如上所述,我已经尝试了所有可能想到的组合。 (现在,请注意有人告诉我在函数名称和参数(例如关键字 const)之后需要它。)

Or maybe 'inline' goes elsewhere. I have tried all possible combinations I could think of, as I explained above. (Now watch someone tell me I need it AFTER the function name and arguments, like the keyword 'const'.)

有人对我做错的事情有任何想法吗?我尝试谷歌搜索正确的答案可能是什么,但没有运气。类中的内联函数甚至是东西吗?

Anyone any ideas on what I am doing wrong? I tried googling what the correct answer might be, but no luck. Are 'inline' functions inside a class even a thing?

推荐答案

内联函数必须在头文件中定义。函数的定义(主体)必须在所有尝试使用该函数的翻译单元中可见。您可以直接在类中定义它。或者您可以在代码中定义它,即在类之外。但是它必须在头文件中,而不是在 .cpp 文件中。

Inline functions have to be defined in header files. The definition (the body) of the function has to be visible in all translation units that attempt to use that function. You can define it directly inside the class. Or you can define it as in your code, i.e. outside of the class. But it has to be in header file, not in .cpp file.

试图在其中定义内联函数 .cpp 文件将使其仅在该 .cpp 文件中可用。尝试在其他 .cpp 文件中使用它会导致链接器错误(即未定义引用错误)。

Attempting to define an inline function in .cpp file will make it usable in that .cpp file only. Trying to use it in other .cpp files will lead to linker errors (i.e. "undefined reference" errors).

这篇关于与类成员一起使用内联说明符时的未定义引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆