在 C++ 中定义静态成员

2022-01-05 00:00:00 static c++

我正在尝试像这样定义一个公共静态变量:

I am trying to define a public static variable like this :

public :
         static int j=0;        //or any other value too

我在这一行遇到编译错误:ISO C++ 禁止非常量静态成员 `j' 的类内初始化.

I am getting a compilation error on this very line : ISO C++ forbids in-class initialization of non-const static member `j'.

  1. 为什么在 C++ 中不允许?

  1. Why is it not allowed in C++ ?

为什么允许初始化 const 成员?

Why are const members allowed to be initialized ?

这是否意味着 C++ 中的静态变量不像 C 中那样用 0 初始化?

Does this mean static variables in C++ are not initialized with 0 as in C?

谢谢!

推荐答案

(1.) 为什么在 C++ 中不允许?

(1.) Why is it not allowed in C++ ?

来自 Bjarne Stroustrup 的 C++ 风格和技术常见问题解答:

类通常在头文件中声明,而头文件通常包含在许多翻译单元中.但是,为了避免复杂的链接器规则,C++ 要求每个对象都有唯一的定义.如果 C++ 允许在类中定义需要作为对象存储在内存中的实体,那么这条规则就会被打破.

A class is typically declared in a header file and a header file is typically included into many translation units. However, to avoid complicated linker rules, C++ requires that every object has a unique definition. That rule would be broken if C++ allowed in-class definition of entities that needed to be stored in memory as objects.

(2.) 为什么允许 const 成员被初始化?

(2.) Why are const members allowed to be initialized ?

[直接说得更好]

(3.) 这是否意味着静态变量在 C++ 中没有用 0 初始化为在 C 中?

(3.) Does this mean static variables in C++ are not initialized with 0 as in C?

据我所知,只要您在 .cpp 中声明静态成员 var,如果您不另外指定,它将被零初始化:

As far as I know, as long as you declare the static member var in a .cpp it will be zero-initialized if you don't specify otherwise:

// in some .cpp
int Test::j; // j = int();

相关文章