Defining static members in C++(在 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'.
为什么在 C++ 中不允许?
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();
这篇关于在 C++ 中定义静态成员的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中定义静态成员
基础教程推荐
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
