#include <iostream>
#include <conio.h>
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; /*这里的x为什么不是全局变量里面的那个值为100的x?如果换成int WithStatic::y = ::x + 1; 使用的就是那个100的X,这是为什么?::不是域的符号吗?*/
void main() {
WithStatic ws;
ws.print();
getch();
}
请赐教!!!!!!!
// VC6、VC7的编译后的输出结果都是:X=1,Y=2。
是域的符号但是前面要加类名
::x表示的是全局域的x,如果要用类域的静态变量应该是
int WithStatic::y = WithStatic::x + 1;
int WithStatic::y = x + 1;
等于
int WithStatic::y = WithStatic::x + 1;
因为前面的WithStatic就为表达式右边打开了WithStatic这个类域。
int WithStatic::y = ::x + 1;
因为这里的::表示全局域,所以::x就是100,最后WithStatic::y就为101