2011年5月12日 星期四

[轉錄] 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() {/*..*/}
//…
}; 
 
 
原文網址: http://www.devx.com/tips/Tip/13148 
 

沒有留言:

張貼留言