C++,错误 : Invalid use of qualified-name

标签 c++ class static-members static-variables

#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/

相关文章:

c++ - 在 2D Vector C++ 中查找重复项

Java:如何使用 "this"访问外部类的实例变量?

java - 这两个java数据结构有什么区别?

c++ - 类的静态数据成员是内部链接还是外部链接?

c++ - 从同一类的专用模板的静态函数访问类模板成员

c++ - 运行 .exe 文件时出现 std::logic 错误

c++ - 我的 C 风格字符串表现得很奇怪

Ruby 异常或错误?

java - "intellij idea"调试静态类

c++ - 为什么输出不是预期的那样?