我有一个关于内联方法的问题。 我正在使用为碰撞模型开发的库。一个负责图形界面的头文件包含函数的声明和实现,但函数没有内联。因此,将这些功能包含在几个翻译单元中是不可能的。 如这里的说明是伪代码我设计来加以说明:内联方法:缺点
LivingBeing.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
Forest.h
#ifndef FOREST_H
#define FOREST_H
#include "LivingBeing.h"
class Forest
{
public:
Forest(int _numberLivingBeings);
private:
int numberLivingBeings;
};
#endif
Forest.cpp
#include "Forest.h"
Forest::Forest(int _numberLivingBeings)
{
numberLivingBeings = _numberLivingBeings;
// Call LivingBeing constructor, methods etc...
}
主。 cpp
#include "Forest.h"
int main()
{
Forest forest = Forest(10);
return 0;
}
此代码不会编译,除非在构造函数LivingBeing和方法呼吸前添加inline关键字。错误信息是:
1>main_test.obj : error LNK2005: "public: __thiscall LivingBeing::LivingBeing(double)" ([email protected]@[email protected]@Z) already defined in Forest.obj
1>main_test.obj : error LNK2005: "public: void __thiscall LivingBeing::breathe(void)" ([email protected]@@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文件中使用这些方法。我通过更改源文件来冒着什么风险?
非常感谢
记住了'inline'关键字 - 如果有的话 - 只是一个提示编译器(内联函数体),以及现代的编译器/连接器可以在链接时内嵌的事情。 – PlasmaHH 2013-02-19 11:38:55
使用'inline'关键字的**优势是代码可能工作。如果许多函数看起来像“LivingBeing :: LivingBeing(double _size){size = _size;结果程序会更小,运行速度更快。 – 2013-02-19 12:11:03