为什么这是一个错误?
int a = 0;
a = 42;
int main()
{
}
我能找到的这种行为的可能匹配项:
(3.4.1/4) A name used in global scope, outside of any function, class or user-declared namespace, shall be declared before its use in global scope.
这会不会是标准的缺陷?
最佳答案
int a = 0; //it is a declaration (and definition too) statement
a = 42; //it is an assignment statement
第二行是错误原因,因为它是一个赋值语句。
在命名空间级别,只允许声明和定义语句。命名空间级别不允许使用赋值语句。
“应在其在全局范围内使用之前声明”(来自规范的引文)意味着以下内容:
int a = 42;
int b = 2 * a; //a is being used here
int c = a + b; //both a and b are being used here
如果您改为定义 type,则:
struct A {}; //definition of A
struct B { A a; }; //a is declared as member of B
//(which means, A is being "used")
void f(const A&, const B&); //both A and B are used in the declaration of f
关于c++ - 在全局命名空间中使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7965749/