Abh*_*eet 7 c++ constructor class-constants
我想知道为什么类的常量数据成员需要在构造函数中初始化,为什么不在其他地方?这样做有什么影响而不是这样做?
我还看到,只有静态常量积分数据才能在类中初始化,而不能在类中初始化非数据成员.
例如: - 假设下面是我的班级声明
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();
};
Run Code Online (Sandbox Code Playgroud)
构造函数定义如下: -
编辑部分:由于之前的构造函数定义示例错误
A::A():a(1),b(9){}
Run Code Online (Sandbox Code Playgroud)
如果我错了,请纠正我.提前致谢.
Alo*_*ave 13
A::A(){
a = 1;
b = 9; // Why we need to initialize this only at the constructor.
}
Run Code Online (Sandbox Code Playgroud)
是不是初始化,但它是分配.
a并且b已经构建,并在这种情况下为它们分配值.在const预选赛中要求该变量未初始化之后改变,使这项任务将打破合同.
这是使用成员初始化列表的初始化.
A::A():a(1),b(9)
{}
Run Code Online (Sandbox Code Playgroud)
您可能想看看我的这个答案,以了解其中的差异:
内部构造函数中的Initializing和Assignment有什么区别?
至于另一个问题,关于只有静态常数积分数据可以在课堂内初始化,请阅读我的答案,其中更详细地解释:
你正在做的不是初始化.它是赋值,因此b=9甚至不会编译,因为b是a const,所以不能为它赋值.它应该被初始化,为此,使用成员初始化列表:
A::A() : a(1), b(9)
{ // ^^^^^^^^^^^^ this is called member-initialization list
}
Run Code Online (Sandbox Code Playgroud)
在C++ 11中,您可以使用就地初始化:
class A{
int a = 1; //C++11 only
const int b = 9; //C++11 only
static const int c = 10; //This works fine (both in C++03 and C++11)
//...
};
Run Code Online (Sandbox Code Playgroud)
因为它是常数,所以它的值不能改变.在构造函数之外的任何其他位置初始化将意味着默认初始化,然后是赋值,对于常量不允许.这相当于这样做:
const int i; // OK
i = 42; // Error!
Run Code Online (Sandbox Code Playgroud)
请注意,在C++ 11中,完成此操作是完全可以的:
struct Foo {
const int i=42;
const double x = 3.1416;
};
Run Code Online (Sandbox Code Playgroud)
但这遵循相同的规则,即没有任务.