这是因为被static声明的类静态数据成员,其实体远在main()函数开始之前就已经在全局数据段中诞生了(见《Inside The C++ Object Model》page247)!其生命期和类对象是异步的,(而且静态语意说明即使没有类实体的存在,其静态数据成员的实体也是存的)这个时候对象的生命期还没有开始,如果你要到类中去初始化类静态数据成员,让静态数据成员的初始化依赖于类的实体,,那怎么满足前述静态语意呢?难道类永远不被实例化,我们就永远不能访问到被初始化的静态数据成员吗?
Ordinarily, class static members, like ordinary data members, cannot be initialized in the class body. Instead, static data members are normally initialized when they are defined.
One exception to this rule is that a const static data member of integral type can be initialized within the class body as long as the initializer is a constant expression:
class Account {
public:
static double rate() { return interestRate; }
static void rate(double); // sets a new rate
private:
static const int period = 30; // interest posted every 30 days
double daily_tbl[period]; // ok: period is constant expression
};
A const static data member of integral type initialized with a constant value is a constant expression. As such, it can be used where a constant expression is
required, such as to specify the dimension for the array member daily_tbl.
When a const static data member is initialized in the class body, the data member must still be defined outside the class definition.
When an initializer is provided inside the class, the definition of the member must not specify an initial value:
// definition of static member with no initializer;
// the initial value is specified inside the class definition
const int Account::period;