何时在带有头文件和目标文件的类方法中使用“inline”关键字
When to use 'inline' keyword in class methods with header and object files?
我一直在调整我的游戏(将类声明放在 *.h 文件中,并在相应的.cpp对象文件中定义它们),但我不太明白什么时候我必须在方法定义旁边使用"inline"关键字,什么时候不这样做。让我向您展示:
//shape.h
//header guards and includes in here
class shape
{
private:
char type;
int verticies[4][2];
int centre[2];
int radius;
public:
shape(int coordinates[4][2]);
shape(int coords[2], int r);
void Change(int coordinates[4][2]);
void Change(int coords[2], int r);
//more functions...
};
//shape.cpp
#include "shape.h"
inline shape::shape(int coordinates[4][2])//Constructor for a rectangle shape
{
for (int i=0; i<8; i++) //copy arguments to class
verticies[i/2][i%2]=coordinates[i/2][i%2];
//calculate centre of the rectangle
centre[0]=(coordinates[0][0]+coordinates[2][0])/2;
centre[1]=(coordinates[0][1]+coordinates[2][1])/2;
}
inline shape::shape(int coords[2], int r)//Constructor for a circle shape
{
type='C';
centre[0]=coords[0];
centre[1]=coords[1];
radius=r;
}
inline void shape::Change(int coordinates[4][2])//change coordinates of a rectangle shape
{
if (type=='C') return;//do nothing if a shape was a circle
for (int i=0; i<8; i++)
verticies[i/2][i%2]=coordinates[i/2][i%2];
centre[0]=(coordinates[0][0]+coordinates[2][0])/2;
centre[1]=(coordinates[0][1]+coordinates[2][1])/2;
if(verticies[0][0]-verticies[1][0]==0 || verticies[0][1]-verticies[1][1]==0) type='S'; else type='R';
}
inline void shape::Change(int coords[2], int r)//change coordinates for a circle shape
{
if (type=='R' || type=='S') return; //do nothing if a shape was not a circle
centre[0]=coords[0];
centre[1]=coords[1];
radius=r;
}
//and so on...
没有内联关键字会导致:"'形状::形状(int (*) [2])'的多重定义"错误。 然而,在其他情况下,其他类使用"内联"是不必要的。所以我的问题是:我什么时候必须使用"内联"关键字,为什么它很重要?
编辑:所以我被告知在这种情况下使用内联是一个坏主意。因此,实现源文件和头文件的正确方法是什么?
在头文件中但在类声明外部定义非模板函数时,inline
关键字很重要。当标头包含在多个位置时,它避免了多重定义问题。
除此之外,这些天没有多大用处。从技术上讲,它仍然应该表明您希望函数使用内联扩展 - 即编译器不是实际调用它(这会带来很小的开销),而是将整个函数体的副本拖放到它被调用的任何位置。(对于非常小的函数(例如访问器方法)来说,这是一个非常宝贵的优化。但实际上,编译器倾向于自己弄清楚应该内联和不应该内联的内容,因此它将关键字视为一个提示。
在您发布的代码版本中,inline
键是完全不必要的,实际上是有害的。在此版本中,您必须从发布的代码中删除所有inline
关键字才能正确编译和链接它。由于缺少函数定义,您发布的内容通常会导致链接器错误。
如果将所有函数定义移动到头文件中,则inline
关键字是必需的。
因此,这是关键字和成员函数必须遵循inline
简单规则:如果在标头 (.h
) 文件中定义成员函数,请使用inline
关键字。如果在实现 ( .cpp
) 文件中定义成员函数,请不要使用 inline
关键字。
- extern 关键字在包含文件头文件C++
- 读取文本文件,其中C++读取特定关键字后面的值
- 使用关键字从文本文件返回数字
- 在特定字段中关键字搜索后,从文本文件中提取多个记录
- 如果我在标题文件中使用关键字的声明,则应该在定义本身中包含相同的关键字
- 如何在.cpp文件中使用C++关键字
- C++:定义类函数的.cpp文件中实例本身的表示关键字
- 如何在文件中搜索关键字,然后打印其中包含的字符串
- 具有多个文件的extern关键字
- 在二进制格式的xml文件中查找关键字
- 何时在带有头文件和目标文件的类方法中使用“inline”关键字
- 在 VC++ 中访问一个文件中声明的变量.(外部关键字用法)
- 使用关键字解析 C++ 中的文件
- C++ 在关键字段上联接两个管道分隔文件
- C++,逐行读取并搜索链接到文件中某行的关键字
- 不能对 c++ 类实现文件中的静态方法使用 "static" 关键字 (.cpp)
- 如果在头文件中定义方法,内联关键字有什么用?
- 这里需要extern关键字,cpp文件中的const
- 头文件与源/实现文件中关键字包含C++ "Rules"
- 当我们在该类的头文件中定义一个类成员函数时,必须使用内联关键字.为什么