[英]Non static const data members
How do I define a non-static const data member of a class in C++? 如何在C ++中定义类的非静态const数据成员? If I try compiling the following code:
如果我尝试编译以下代码:
class a
{
public:
void print()
{
cout<<y<<endl;
}
private:
const int y=2;
};
int main()
{
a obj;
obj.print();
}
I get an error 我得到一个错误
ISO C++ forbids initialization of member ‘y’
In C++03 you can initialize const
fields of a class using a member-initializer list in the constructor. 在C ++ 03中,可以使用构造函数中的成员初始化器列表来初始化类的
const
字段。 For example: 例如:
class a
{
public:
a();
void print()
{
cout<<y<<endl;
}
private:
const int y;
};
a::a() : y(2)
{
// Empty
}
Notice the syntax : y(2)
after the constructor. 注意构造函数后的语法
: y(2)
。 This tells C++ to initialize the field y
to have value 2. More generally, you can use this syntax to initialize arbitrary members of the class to whatever values you'd like them to have. 这告诉C ++将字段
y
初始化为具有值2。更一般而言,您可以使用此语法将类的任意成员初始化为您希望它们具有的任何值。 If your class contains const
data members or data members that are references, this is the only way to initialize them correctly. 如果您的类包含
const
数据成员或作为引用的数据成员,则这是正确初始化它们的唯一方法。
Note that in C++11, this restriction is relaxed and it is fine to assign values to class members in the body of the class. 请注意,在C ++ 11中,放宽了此限制,可以在类主体中为类成员分配值是很好的。 In other words, if you wait a few years to compile your original code, it should compile just fine.
换句话说,如果您等了几年才编译原始代码,那么它应该可以编译。 :-)
:-)
Initialize it in the constructor initialization list. 在构造函数初始化列表中对其进行初始化。
class a
{
const int y;
public:
a() : y(2) { }
};
You can't use an initializer inside the class definition. 您不能在类定义内使用初始化程序。 You need to use the constructor initialization instead:
您需要使用构造函数初始化:
a::a() : y(2) {}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.