STL容器[30]

index.cpp:59: in-class initialization of static data member of non-integral type `const string'
index.cpp:60: in-class initialization of static data member of non-integral type `const string'
index.cpp:61: in-class initialization of static data member of non-integral type `const string'

 

Static Class Members may not be Initialized in a Constructor

A common mistake is to initialize static class members inside the constructor body or a member-initialization list like this:


class File
{
private:
static bool locked;
private:
File();
//…
};
File::File(): locked(false) {} //error, static initialization in a member initialization list

Although compilers flag these ill-formed initializations as errors, programmers often wonder why this is an error. Bear in mind that a constructor is called as many times as the number of objects created, whereas a static data member may be initialized only once because it is shared by all the class objects. Therefore, you should initialize static members outside the class, as in this example:


class File
{
private:
static bool locked;
private:
File() { /*..*/}
//…
};
File::locked = false; //correct initialization of a non-const static member

Alternatively, for const static members of an integral type, the Standard now allows in-class initialization:


class Screen
{
private:
const static int pixels = 768*1024; //in-class initialization of const static integral types
public:
Screen() {/*..*/}
//…
};
posted @ 2009-12-24 16:11  酱油和醋  阅读(242)  评论(0编辑  收藏  举报