c++,错误:限定名称的使用无效
c++, error: Invalid use of qualified-name
#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
初始化,这是一个语法错误。
相关文章:
- 在没有参数列表的情况下使用模板名称"Event"无效,模板问题
- 为什么右值不能绑定到非常量左值引用,除了写入临时无效的事实?
- 模板化的模板参数名称在方法头上无效
- 调用boost v1.58中的函数时出现模板名称使用无效错误
- HTTP 请求中的标头名称无效
- Clang 3.8 错误:参数 '-fuse-ld=gold-2.25' 中的链接器名称无效
- 在没有参数列表的情况下无效使用模板名称"节点"
- Android NDK Linker (GStreamer) - 无效的链接器名称 -fuse-ld=gold.
- 如何使用libpq库和C 绑定无效的语句
- C++中名称查找和名称绑定之间的区别
- 如何在没有参数列表的情况下定义向量无效使用模板名称 std::vector
- 错误:在没有参数列表的情况下无效使用模板名称“ExTree” ||如果解决这个问题怎么办?(初学者)
- C++代码编译失败,错误"长类型名称"无效
- 没有参数列表的模板名称使用无效
- C++ - 运行 Moses 解码器时区域设置名称无效异常
- 模板名称使用无效
- 使用 VS2012 编译库时符号名称无效
- 抛出 'std::runtime_error' what() 的实例:区域设置::facet::_S_create_c_locale 名称无效
- 没有参数列表的模板名称使用无效
- Sample.exe中0x7537812f处未处理的异常:0xC0020001:字符串绑定无效