在头文件中内联 class 方法

Inline class method in the header file

下面的实现有什么区别吗?

class Foo
{
     int bar(int x) const
     { return x * 2; }
};


class Foo
{
     inline int bar(int x) const
     { return x * 2; }
};

当函数被标记为inline时,它告诉编译器将函数的代码放到函数被调用的地方。你可以有隐式和显式内联 - 类 的成员函数是隐式内联的,所以你不需要输入它,在你的情况下没有区别。

根据 C++ 标准(9.3 成员函数)

2 A member function may be defined (8.4) in its class definition, in which case it is an inline member function (7.1.2), or it may be defined outside of its class definition if it has already been declared but not defined in its class definition.

3 An inline member function (whether static or non-static) may also be defined outside of its class definition provided either its declaration in the class definition or its definition outside of the class definition declares the function as inline.

7.1.2 函数说明符

3 A function defined within a class definition is an inline function. The inline specifier shall not appear on a block scope function declaration. 94 (The inline keyword has no effect on the linkage of a function.) If the inline specifier is used in a friend declaration, that declaration shall be a definition or the function shall have previously been declared inline.

所以,没有。没有区别。