为什么在C++中静态成员函数_declared_static,而_defined_theotherwise

Why is a static member function _declared_ static, but _defined_ otherwise in C++?

本文关键字:static defined theotherwise declared 为什么 C++ 静态成员 函数      更新时间:2023-10-16

这里有一个最小的工作示例:

A.h:

class A{
static int a_member_function();
};

A.cpp

#include "A.h"
int A::a_member_function(){return 5;}

int main(){ return 1;}

这段代码编译并运行,但是,在我看来:

static int A::a_member_function(){return 5;}

可以很容易地用于定义类A的静态成员函数。事实上,有这个要求似乎实际上很有用,因为它会提醒.cpp文件的读者A_member_function是静态的。

然而,这显然不起作用:

error: cannot declare member function ‘static int A::a_member_function()’ to have static linkage [-fpermissive]

那么为什么不起作用?这个决定背后的原因是什么?

背后的原因是C++精神,即尽量减少关键字的数量,并保持与C:static的向后兼容性,在这个位置上有着完全不同的意义。

这一切都早于C。C中的"静态"函数是编译单元(.C文件)独有的函数。其他编译单元无法访问它们(这是用C进行封装的一种方式)。这种用法在C++中仍然有效。您也可以对全局变量执行同样的操作,以限制它们的范围。

不过,在C++中,您也希望将成员函数声明为static,原因不同:这些函数属于类,但不需要运行所述类的实例(我打赌您已经知道了,我只是想做到完整)。

将成员函数定义为static会导致矛盾:必须在其翻译单元之外访问该函数。

C和C++之间还有另一种关键字重用的情况,即C++11中的auto关键字,但这不太可能成为问题。

注意:virtual关键字也会发生同样的情况,它出现在声明中,而不是定义中。