c++ - 在全局命名空间中使用变量

标签 c++

为什么这是一个错误?

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/

相关文章:

c++ ostringstream 提高 IO 性能?

c# - 如何在 Windows 8/8.1 中显示 "Set program associations"窗口?

C++如何读取流直到行尾

c++ - 右移和有符号整数

javascript - 如何只匹配那些前面有偶数个 `%` 的数字?

c++ - 二进制搜索到实数函数的上限

c++ - 在 C++ 中,类型名称的 typeid 总是在编译时求值吗?

c++ - 哈希表和二维 vector

c++ - boost::posix_time::ptime 到 UTC8601?

c++ - 基于模板的设计意见