c++,错误:限定名称的使用无效

c++, error: Invalid use of qualified-name

本文关键字:无效 定名称 错误 c++      更新时间:2023-10-16
#include<iostream>
using namespace std;
class sample {
    public:
        static int x;
};
//int sample::x = 20;
int main() {
    sample s1;
    int sample::x = 30;
}

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

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

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

正如标准所说:

静态数据成员的定义应出现在包含成员类定义的命名空间作用域中。

此外,静态数据成员的定义在类的范围内。所以

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)

您必须在全局命名空间中为其分配空间

#include<iostream>
class sample {
    public:
        static int x;
};
int sample::x = 20;
int main() {
    sample s1;
    sample::x = 30;
}

您可以在main或任何其他方法中正常设置n。这是关于静态关键字的教程。我删除了 using 指令,因为引入整个命名空间是一种不好的做法,尤其是当您不需要它时。

静态 var

需要初始化的原因是全局范围,因为静态和全局 var 都有静态存储持续时间

您不能在函数中定义静态变量,但必须在任何范围之外执行此操作:尝试

int sample::x = 30;
int main() {
    sample s1;
}

相反。不过,您可以执行以下操作:

int sample::x = 30;
int main() {
    sample s1;
    sample::x = 42; // Note the different syntax!
}

静态成员就像全局对象一样只能通过sample::x

您必须在定义类的全局范围内初始化它们。

所以你不能用main初始化,这是一个语法错误。