My C++ compiler complains when i try to initialize a int member variable in class definition. It tells "only static const integral data members can be initialized within a class". Can you please explain the rationale behind this restri开发者_如何学Pythonction (if possible with example).
Because it's not allowed in the current standard. According to Bjarne, you will be able to do this in C++0x. If you really need it, try setting the compiler to C++0x (-std=c++0x
in GCC) and see if your compiler supports it.
The rationale is the "low-level" nature of C++. If it would allow this, the compiler would need to generate initialization code for all constructors which is not entirely clear to the developer.
After all it might be necessary to initialize members of base classes on the construction of a derived class even when the base class constructors are not explicitly invoked.
Static const integral variables do not need intitalization upon object creation.
The static restriction exists because C++ uses constructor initializers to initialize non-static data members:
struct Example {
int n;
Example() : n(42) {}
};
The const restriction exists because the const case is treated specially (rather than the other way around) so that static const integral members can usually be treated as if they had internal linkage, similar to const variables at namespace scope (C++03 §7.1.5.1p2, if you're interested). This is primarily beneficial to use the members in integral constant expressions, such as array sizes.
I'm just guessing you're trying to do this:
class foo {
int m_iX = 5;
};
This would require code to be run in the constructor, since every newly created instance would need to initialize this variable. In C++, all code that is run during the constructor is (luckily) contained in the constructor itself, so it is immediately obvious what the construction of the class entails. Furthermore, since a class can have any number of constructors (including copy constructors), it would be ambiguous as when this initialization should or should not take place.
You can do this:
class foo {
enum {
CONSTANT = 8
};
};
This allows you to use foo::CONSTANT
. That works since it will be per-class rather than per-instance.
Likewise, you can do this:
class foo {
static int sm_iX;
};
in the .cpp:
int foo::sm_ix = 5;
Again, this is per-class, not per-instance, and as such not relevant to the construction of an actual instance.
Bonus - if you declare this int const, many compilers might evaluate it at compile-time.
Arun,
I believe your question is related to
Compiler Error C2864
To achieve what you want to do, C++ requires you to initialize instance specific members (ie: non static, non cost) either in Constructor body or the initialization list.
精彩评论