错误,因为"static" C++代码

Error because "static" at C++ code

本文关键字:C++ 代码 static 错误 因为      更新时间:2023-10-16

我正在介绍c ++的oop,我有一个问题。当我在头文件中将函数声明为静态时,如果我在代码文件中也放置静态,为什么会出现错误?我的意思是,为什么静态应该只在头文件上?

月经错误:

mod.cc:71:40:错误:无法声明成员函数"static int mod::mida_maxima()"以具有静态链接 [-fallowive]

class中的static成员函数是一个类函数;它在没有任何接收器的情况下工作,因此this不能在其中使用。但是,在任何编译单元中都可以看到它的声明。

当你定义一个static函数时,它具有static链接,因此只能从其编译单元中可见(有点像 C 的 static 关键字)。显然,类函数通常应该从整个程序中可见(而不仅仅是单个编译单元)。

因此,static成员函数的定义不应该static,换句话说:

 // perhaps in a header file
 class Foo {
   static void memberfun (int); // class member function declaration
 };
 // definition in the compilation unit
 void // static is forbidden here 
 Foo::memberfun(int arg) {
   /// some body
 }

换句话说,C++将 static 关键字重用于两个不相关的目的:成员的定义和静态链接的声明(受 C 的启发)。