c++ - 什么时候在带有头文件和目标文件的类方法中使用 'inline' 关键字?

标签 c++ methods inline declaration definition

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

没有内联关键字会导致:“多重定义 `shape::shape(int (*) [2])'”错误。然而,在其他情况下,其他类使用“内联”是不必要的。所以我的问题是:我什么时候必须使用“内联”关键字,为什么它仍然很重要?

编辑:所以我被告知在这种情况下使用内联是一个坏主意。那么,什么是实现源文件和头文件的正确方法?

最佳答案

当您在头文件中但在类声明之外定义非模板函数时,inline 关键字很重要。当标题包含在多个位置时,它避免了多重定义问题。

除此之外,这些天它用处不大。从技术上讲,它仍然应该表明您希望函数使用内联扩展——即编译器不会实际调用它(这会带来很小的开销),而是将整个函数体的拷贝放入调用它的任何位置。 (对于非常小的函数,例如访问器方法,这是一个非常宝贵的优化。)但实际上,编译器往往会自己弄清楚什么应该内联,什么不应该内联,所以它只把关键字当作一个提示。

关于c++ - 什么时候在带有头文件和目标文件的类方法中使用 'inline' 关键字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19867815/

相关文章:

c++ - 将 const char* 类型转换为 int 数组

c++ - 一次处理许多流操作

c++ - 正确查找字符串中的数字?

c++ - 成员函数与传递对全局函数的引用相同吗?

c - 具有 C99 内联函数的 OpenBSD 5.9 header

c++ - QTableView选择单个单元格

c# - yield return 语句如何不返回任何元素?

java - 为什么我的重载静态方法无法识别我的高度参数?

.net - ILGenerator 方法内联

html - 使 div 的宽度适应包含多个 div 的内容