- #include <iostream>
- using namespace std;
-
- class A
- {
- static int x; // 实现数据共享, 所有该类产生的对象都共用这个x, 比全局变量好。
- };
-
- int A::x = 100;
-
- int main()
- {
- A a;
-
- return 0;
- }
如此一来, 似乎是对私有的变量在类外进行直接访问了啊, 这岂不是违背了类的保护性机制么? 其实没有。 注意:static int x; 是变量的初始化, 而且只能在类体外, 且类外不能直接访问。如:
- #include <iostream>
- using namespace std;
-
- class A
- {
- static int x;
- };
-
- int A::x = 100;
-
- int main()
- {
- A a;
- cout << a.x << endl; // error
- cout << A::x << endl; // error
-
- return 0;
- }
另外, 书上说, 如果一个静态数据成员声明了,但未被定义, 会有连接错误, 但我貌似没有在VC++6.0中看到错误啊:
- #include <iostream>
- using namespace std;
-
- class A
- {
- static int x;
- };
-
- int main()
- {
- A a;
-
- return 0;
- }