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

标签 c++ constants

#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/

相关文章:

c++ - C++ 中的模板引用参数推导失败

c++ - 为什么忽略返回类型 'cv'?

c++ - 在 C++ 中转储局部变量

c++ - 开关盒错误 |的值在常量表达式中不可用

c++ - "get() const"与 "getAsConst() const"

objective-c - const 是在 CGFloat 之前还是之后?

c++ - GetFileAttributesA 为现有目录返回 "17"。 "16"表示它是一个目录,文档中没有提到 "17"

c++ - 我可以将 int 与 C++ 中的 boolean 值相乘吗?

c++ - 如何处理我的 C++ __getitem__ 函数中的切片(由 SWIG 使用)

c++ - 有符号和无符号整数表达式之间的比较