How to initialize const member variable in a class?(如何在类中初始化 const 成员变量?)
问题描述
#include <iostream>
using namespace std;
class T1
{
const int t = 100;
public:
T1()
{
cout << "T1 constructor: " << t << endl;
}
};
当我尝试用 100 初始化 const 成员变量 t
时.但它给了我以下错误:
When I am trying to initialize the const member variable t
with 100. But it's giving me the following error:
test.cpp:21: error: ISO C++ forbids initialization of member ‘t’
test.cpp:21: error: making ‘t’ static
如何初始化 const
值?
推荐答案
const
变量指定变量是否可修改.每次引用变量时都将使用分配的常量值.在程序执行期间不能修改分配的值.
The const
variable specifies whether a variable is modifiable or not. The constant value assigned will be used each time the variable is referenced. The value assigned cannot be modified during program execution.
Bjarne Stroustrup 的解释 简要总结:
Bjarne Stroustrup's explanation sums it up briefly:
一个类通常在头文件中声明,并且头文件通常包含在许多翻译单元中.但是,为了避免复杂的链接器规则,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.
const
变量必须在类中声明,但不能在其中定义.我们需要在类外定义 const 变量.
A const
variable has to be declared within the class, but it cannot be defined in it. We need to define the const variable outside the class.
T1() : t( 100 ){}
这里的赋值 t = 100
发生在初始化列表中,远在类初始化发生之前.
Here the assignment t = 100
happens in initializer list, much before the class initilization occurs.
这篇关于如何在类中初始化 const 成员变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何在类中初始化 const 成员变量?


基础教程推荐
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09