因为类的静态数据成员有着单一的存储空间而不管产生了多少个对象,所以存储
空间必须在一个单独的地方定义
定义必须出现在类的外部 不允许内联 而且只能定义一次,因此它突出放在一个
类的实现文件中
静态成员的初始化表达式是在一个类的作用域内
//: C10:Statinit.cpp
// From Thinking in C++, 2nd Edition
// Available at http://www.BruceEckel.com
// (c) Bruce Eckel 2000
// Copyright notice in Copyright.txt
// Scope of static initializer
#include <iostream>
using namespace std;
int x = 100;
class WithStatic {
static int x;
static int y;
public:
void print() const {
cout << "WithStatic::x = " << x << endl;
cout << "WithStatic::y = " << y << endl;
}
};
int WithStatic::x = 1;
int WithStatic::y = x + 1;
// WithStatic::x NOT ::x
int main() {
WithStatic ws;
ws.print();
getchar();
} ///:~
这里,withStatic::限定符把withStatic的作用域扩展到全部定义中
输出
WithStatic::x = 1
WithStatic::y = 2