我有一个关于内联方法的问题。 我正在使用为碰撞模型开发的库。一个负责图形界面的头文件包含函数的声明和实现,但函数不是内联的。因此,不可能将这些功能包含在多个翻译单元中。 作为示例,这里是我为示例设计的虚拟代码:
活人.h
#ifndef LIVINGBEING_H
#define LIVINGBEING_H
class LivingBeing
{
public:
LivingBeing(double _size);
void breathe();
private:
double size;
};
//////////////
LivingBeing::LivingBeing(double _size)
{
size = _size;
}
void LivingBeing::breathe()
{
// do something
}
#endif
森林.h
#ifndef FOREST_H
#define FOREST_H
#include "LivingBeing.h"
class Forest
{
public:
Forest(int _numberLivingBeings);
private:
int numberLivingBeings;
};
#endif
森林.cpp
#include "Forest.h"
Forest::Forest(int _numberLivingBeings)
{
numberLivingBeings = _numberLivingBeings;
// Call LivingBeing constructor, methods etc...
}
main.cpp
#include "Forest.h"
int main()
{
Forest forest = Forest(10);
return 0;
}
除非我在构造函数 LivingBeing 和方法 breathe 前面添加 inline 关键字,否则这段代码不会编译。错误信息是:
1>main_test.obj : error LNK2005: "public: __thiscall LivingBeing::LivingBeing(double)" (??0LivingBeing@@QAE@N@Z) already defined in Forest.obj
1>main_test.obj : error LNK2005: "public: void __thiscall LivingBeing::breathe(void)" (?breathe@LivingBeing@@QAEXXZ) already defined in Forest.obj
1>C:\Users\******\Documents\Visual Studio 2010\Projects\TutorialChronoEngine\Debug\Test_3.exe : fatal error LNK1169: one or more multiply defined symbols found
我的问题是:内联方法有什么缺点?我使用的真实库非常大,我想从特定文件(在我的示例中是 LivingBeing.h)中内联方法,以便可以在多个 .cpp 文件中使用这些方法。这样更改源文件有什么风险?
非常感谢
最佳答案
您正在标题中定义函数(LivingBeing::LivingBeing
和 LivingBeing::breathe
),这意味着每个翻译单元中都会有一个定义,其中包括 header 。这违反了单一定义规则 (ODR),因此出现链接错误。
你有三个选择:
- 将函数定义移动到源文件中,这样它们只定义一次;或
- 将它们声明为
内联
以允许多个相同的定义;或 - 将定义移动到类定义中,这隐式地使它们
内联
。
what is the drawbacks of inlining methods ?
- 可能会增加编译时间和可执行文件的大小;但您需要测量以查看是否存在任何明显差异。
- 不太稳定的 API - 每当任何内联函数发生变化时,客户端代码都需要重新编译。
- 意外破坏 ODR 的可能性,例如,如果函数包含在不同翻译单元中可能具有不同扩展的宏。
关于c++ - 内联方法 : drawbacks,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14955846/