#include<iostream>
using namespace std;
class sample {
public:
static int x;
};
//int sample::x = 20;
int main() {
sample s1;
int sample::x = 30;
}
当我编译这个程序然后得到一个错误 Invalid use of qualified-name 'sample::x'
我知道我收到这个错误是因为 main 中的这个语句 int sample::x = 30;。
但我不明白为什么我不能在main中定义int sample::x = 30;?
最佳答案
正如标准所说:
The definition for a static data member shall appear in a namespace scope enclosing the member’s class definition.
此外,静态数据成员的定义是在类的范围内。 所以,
int x = 100; //global variable
class StaticMemeberScope
{
static int x;
static int y;
};
int StaticMemeberScope::x =1;
int StaticMemeberScope::y = x + 1; // y =2 (StaticMemeberScope::x, not ::x)
关于C++,错误 : Invalid use of qualified-name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18000727/