何时在带有头文件和目标文件的类方法中使用“inline”关键字

When to use 'inline' keyword in class methods with header and object files?

本文关键字:文件 关键字 inline 类方法 目标 何时      更新时间:2023-10-16

我一直在调整我的游戏(将类声明放在 *.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 关键字。