How do I define a non-static const data member of a class in C++? 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. 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. 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. If your class contains const
data members or data members that are references, this is the only way to initialize them correctly.
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. 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) {}
精彩评论