2011-11-01 117 views
0

为什么这应该是一个错误?变量在全局命名空间中的使用

int a = 0; 
a = 42; 

int main() 
{ 
} 

这种行为的possibe比赛我能找到的:

(3.4.1/4)在全球范围内使用,任何功能之外的姓名,班级 或用户声明的命名空间,应在全球范围内使用前予以声明 范围。

这可能是标准缺陷吗?

+0

不,这不是标准的缺陷。你引用的部分意味着你需要为你想使用的所有名字声明_before_你使用它们。这并不意味着你可以在全球范围内做任何你想做的事情。 – Mat

+0

在全球范围内使用它们之前它是什么意思? – user103214

+0

'struct A {};一个foo();''名称'A'用于'foo()'的声明中。 – Mat

回答

7
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 

如果定义代替,则:

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 
+1

好吧,这是一个表达声明,确切地说。赋值是一个表达式,而不是一个声明。 –

+0

@CatPlusPlus:如果一个包含';',那么它就成为语句。 – Nawaz

+0

是的,一个表达式语句。 –

1

您不能在全局命名空间中编写这样的赋值语句

它需要在主要或某些[成员]功能

int main() 
{ 
    a=42; 

    return 0; 
}