c ++,错误:使用qualified-name无效

Dix*_*gla 2 c++ class static-variables static-members

#include<iostream>
using namespace std;

class sample {
    public:
        static int x;
};

//int sample::x = 20;

int main() {
    sample s1;
    int sample::x = 30;
}
Run Code Online (Sandbox Code Playgroud)

当我编译这个程序然后得到一个错误无效使用限定名称'sample :: x'

我知道我收到此错误是因为这个语句是int sample :: x = 30; 在主要.

但我不明白为什么我不能定义 int sample :: x = 30; 在主?

Uch*_*chi 6

正如标准所说:

静态数据成员的定义应出现在包含成员类定义的命名空间范围内.

此外,静态数据成员的定义属于类的范围.所以,

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)
Run Code Online (Sandbox Code Playgroud)