在我看来,静态类变量与外部变量相同,因为您只在 static int x
/extern int x 中声明它
语句,并实际在别处定义它(通常在 .cpp 文件中)
静态类变量
// .h file
class Foo
{
static int x ;
} ;
// .cpp file
int MyClass::x = 0 ;
外部变量:
// .h file
extern int y;
// .cpp file
int y = 1;
在这两种情况下,变量都在某处声明一次,并在一个文件中定义,该文件不会在编译中多次包含(否则链接器错误)
最佳答案
是的,两者都有静态存储时长和外部链接;它们具有基本相同的运行时属性,只是(编译时)可见性不同。
关于c++ - 静态类变量是否与外部变量相同,仅具有类范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7917500/