为什么在C++中静态成员函数_declared_static,而_defined_theotherwise
Why is a static member function _declared_ static, but _defined_ otherwise in C++?
这里有一个最小的工作示例:
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
关键字也会发生同样的情况,它出现在声明中,而不是定义中。
相关文章:
- 为什么即使使用-cudart-static进行编译,库用户仍然需要链接到cuda运行时
- 如何处理 c++ 中类实现中的"invalid use of non-static data member"?
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- "Ill-defined for-loop - loop executes infinitely" (MSVC C6295)
- 收到错误"invalid use of non-static data member 'stu::n' "
- LNK1104:无法打开libpjproject-i386-Win32-vc14-Debug-Static.lib
- 我应该在 C++ 中何时/为什么使用 STATIC?
- 使用"std::enable_if_t" "function template has already been defined"
- 在VS2019项目中集成ImageMagick:x64-windows-static library
- 如果两个静态库使用相同的另一个静态库,如何避免"LNK2005 Already Defined error"?
- 如何处理Boost Spirit X3导致Visual Studio 2019 "static initialization order fiasco"?
- 使用 gtest 时"_main already defined"
- "static char __ = []() -> char"的含义
- 当初始值设定项是基类名时'initializer does not name a non-static data member or base class'错误
- 无法在 DLL 中链接 SDL2-static.lib
- 如何摆脱C++中未解析的外部符号"private: static char"错误?
- 为什么"types may not be defined in parameter types"
- C++线程"Call to non-static member function without an object argument"
- 如何将指向 C 中函数的"DEFINED"常量的指针传递给函数?
- 出现这种错误的原因是什么"invalid use of non-static data member "