我想知道为什么类的常量数据成员需要在构造函数中初始化,为什么不在其他地方初始化?这样做和不这样做有什么影响?
我也看到只有静态常数积分数据可以在类内部初始化,但不能在类内部初始化任何数据成员。
例如:- 假设下面是我的班级声明
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();
};
构造函数定义如下:-
编辑部分:由于之前的构造函数定义示例是错误的
A::A(){
a = 1;
b = 9; // Why we need to initialize this only at the constructor.
}
Is 不初始化但它是任务.
a
and b
已经构造好了,在这种情况下您可以为它们分配值。这const
限定符要求变量在初始化后不得更改,允许此分配将破坏该约定。
这是初始化使用成员初始化列表.
A::A():a(1),b(9)
{}
您可能想看看我的这个答案,以了解其中的区别:
构造函数中的初始化和赋值有什么区别? https://stackoverflow.com/questions/1711990/what-is-this-weird-colon-member-syntax-in-the-constructor/8523361#8523361
至于另一个问题,关于只能在类内部初始化静态常量积分数据,请阅读我的这个答案,其中有更详细的解释:
为什么我无法在类中初始化非常量静态成员或静态数组? https://stackoverflow.com/questions/9656941/why-i-cant-initialize-non-const-static-member-or-static-array-in-class/9657064#9657064
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)