gpt4 book ai didi

c++ - 如何在类中初始化 const 成员变量?

转载 作者:IT老高 更新时间:2023-10-28 11:56:40 30 4
gpt4 key购买 nike

#include <iostream>

using namespace std;
class T1
{
const int t = 100;
public:

T1()
{

cout << "T1 constructor: " << t << endl;
}
};

当我尝试用 100 初始化 const 成员变量 t 时。但它给了我以下错误:

test.cpp:21: error: ISO C++ forbids initialization of member ‘t’
test.cpp:21: error: making ‘t’ static

如何初始化 const 值?

最佳答案

const 变量指定变量是否可修改。每次引用变量时都将使用分配的常量值。在程序执行期间不能修改分配的值。

Bjarne Stroustrup 的 explanation简单总结一下:

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 变量。

T1() : t( 100 ){}

这里的赋值 t = 100 发生在初始化列表中,远在类初始化发生之前。

关于c++ - 如何在类中初始化 const 成员变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14495536/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com