Are static class variables the same as extern variables, only with class scope?

戏子无情 提交于 2020-01-01 10:12:36

问题


It seems to me that a static class variable is identical to an extern variable, because you only declare it in the static int x / extern int x statement, and actually define it elsewhere (usually in a .cpp file)

static class variable

// .h file
class Foo
{
    static int x ;
} ;

// .cpp file
int MyClass::x = 0 ;

Extern variables:

// .h file
extern int y;

// .cpp file
int y = 1;

In both cases the variable is declared once somewhere, and defined in a file that will not be included more than once in the compilation (else linker error)


回答1:


Yes, both have static storage duration and external linkage; they have essentially the same run-time properties, only differing in (compile-time) visiblity.




回答2:


More or less. Both have external linkage, and static lifetimes. Both will be initialized on program start-up, and destructed on exit.




回答3:


Yes.

As an additional info, in some programming languages that use non optional namespaces / modules, static class variables can be exchanged with global variables.

In some cases, those other programming variables, doesn't even have static class variables, and you may use global variables, instead.

Some developers prefer use static class variables, enforcing its relation with the class.

Its also a matter of how are you designing your application, even if both features are available.



来源:https://stackoverflow.com/questions/7917500/are-static-class-variables-the-same-as-extern-variables-only-with-class-scope

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!