如何在类C ++中初始化const成员变量 [英] how to initialize const member variable in a class C++

查看:437
本文介绍了如何在类C ++中初始化const成员变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream>

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

  T1()
  {

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

当我试图初始化const成员变量 t with 100.它给出的错误像

When I am trying to initialize the const member variable t with 100. Its giving error like

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

一个?

推荐答案

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.

通常在头文件和头文件通常包括在许多翻译单元中。但是,为了避免复杂的链接器规则,C ++要求每个对象都有唯一的定义。如果C ++允许需要在内存中作为对象存储的实体的类定义,那么该规则将被破坏。

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.

A 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.

这篇关于如何在类C ++中初始化const成员变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆