开发者

ios_base and static members

开发者 https://www.devze.com 2023-02-28 10:40 出处:网络
Static constants in the ios_base class are initialized when created, which makes sense for constants.Can non-constant static member variables be initialized the same way, or is this concept only allow

Static constants in the ios_base class are initialized when created, which makes sense for constants. Can non-constant static member variables be initialized the same way, or is this concept only allowed for constant static members?

For non-constant static members with gnu compilers must use always开发者_开发百科 define/allocate space separately from it's deceleration in the header? Is it even proper to initialize constant static members this way?


Class members can be created and initialized only for the static const (integral data type, like int, char, double etc.) members in current C++ standard. For non-static member it's not possible. However, in C++0x that facility is introduced.

Edit: For non-const static member, you can do initialization but you have to do the same in .cpp file (for non template classes). e.g.

struct A
{
  static const int i = 0; // ok
  static int j;  // can declare in .cpp file as below
  int k = 2; // error, but valid in C++0x
  const int l = 3; // error, valid in C++0x
  static const int m[2] = {1,2}; // error, should be an integral type
  static const string n = "hi"; // error, should be an integral type
};
int A::j = 1  // declare in class body, and define outside


Because static data members must be explicitly defined in exactly one compilation unit.

From C++ FAQ http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.12

You might want to read the whole "Constructors" section about "static data member" to clearly understand it. http://www.parashift.com/c++-faq-lite/ctors.html

0

精彩评论

暂无评论...
验证码 换一张
取 消