为什么类的常量数据成员需要在构造函数中初始化? [英] Why constant data member of a class need to be initialized at the constructor?

查看:558
本文介绍了为什么类的常量数据成员需要在构造函数中初始化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么类的常量数据成员需要在构造函数初始化,为什么不在别的地方?



我也看到只有 静态常数积分数据



例如: - 假设下面是我的类声明

/ em>

  class A {
int a; //这个我们可以在构造函数初始化,或者我们可以通过调用vSet成员函数
设置这个成员const int b;
static const int c = 10; // this work fine
public:
A();
〜A();
void vSet(int a);
int iAdd();
void vDisplay();
};

构造函数定义如下: -



已编辑部分:由于之前的构造函数定义示例错误了

  A :: A():a(1),b(9){} 


b $ b

如果我错了,请纠正我。
提前感谢。

解决方案

  A :: A b $ ba = 1; 
b = 9; //为什么我们只需要在构造函数中初始化它。
}

未初始化 >

a b 已经构造,并且在这种情况下为它们分配值。 const 限定符要求变量在初始化之后不会被更改,从而允许此赋值将破坏该合约。



这是使用成员初始化列表的初始化。

  A :: A():a ,b(9)
{}

您可能想看看这个答案我知道区别:








对于另一个问题,关于只能在类中初始化静态常数积分数据,请阅读这个答案,详细解释: / p>

为什么我无法在类中初始化非const静态成员或静态数组?


I want to know why constant data member of a class need to be initialized at the constructor and why not somewhere else? What is the impact of doing so and not doing so?

I also see that only static constant integral data can be initialized inside the class other than that non of the data members can be initialized inside the class.

for eg:- Suppose below is my class declaration

class A{
     int a; // This we can initialize at the constructor or we can set this member by calling "vSet" member function
     const int b;
     static const int c = 10; //This works fine
public:
     A();
     ~A();
     void vSet(int a);
     int iAdd();
     void vDisplay();    
};

And the constructor is defined as mentioned below:-

Edited Section: As previous constructor definition example was wrong

 A::A():a(1),b(9){}

Please correct me if I am wrong. Thanks in advance.

解决方案

A::A(){
      a = 1;
      b = 9; // Why we need to initialize this only at the constructor. 
   }

Is not initialization but it is Assignment.
a and b are already constructed and you assign them values in this case. The const qualifier demands that the variable not be changed after its initialization, allowing this assignment would break that contract.

This is Initialization using Member Initialization list.

A::A():a(1),b(9)
{}

You might want to have a look at this answer of mine to know the difference:

What is the difference between Initializing and Assignment inside constructor?


As for another question, regarding only static constant integral data can be initialized inside the class, please read this answer of mine which explains in greater detail:

Why I can't initialize non-const static member or static array in class?

这篇关于为什么类的常量数据成员需要在构造函数中初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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