为什么编译器接受模棱两可的变量定义
Why does the compiler accept an ambiguous variables definitions?
我有这么一小段代码:
//example1
namespace
{
int a;
}
int a;
main()
{
a++;
return 0;
}
当然,g++ 4.6.1编译器不能编译它并输出一个错误:
./temp.cpp: In function ‘int main()’:
./temp.cpp:10:5: error: reference to ‘a’ is ambiguous
./temp.cpp:6:5: error: candidates are: int a
./temp.cpp:2:9: error: int {anonymous}::a
没关系!
但是当我在main函数中删除对变量"a"的引用时,程序被编译得很好:
//example2
namespace
{
int a;
}
int a;
main()
{
return 0;
}
1)为什么g++编译器允许定义变量"a",而在这种情况下它不允许引用它?
2)这只是g++编译器的特性,没有其他编译器能够编译这样的代码(example2)?
3) g++编译器是否有相应的标志来解释这些代码(example2)为错误?
非常感谢大家!
第二个例子是有效的,因为您仍然可以从翻译单元外部访问全局a
。
匿名命名空间中的a
提供了具有内部链接的变量的定义。全局命名空间作用域中的a
是具有外部链接的变量的定义。您可以在不同的翻译单元中声明extern int a;
并使用它。
不能从main
引用匿名命名空间中的a
并不意味着代码无效。
匿名命名空间中的a
仍然可以在匿名命名空间中被引用。
全局a
可以从任何地方引用(您必须在main
中使用::a
来消除歧义)。
简短的回答是"因为这没有什么违法的"。它只是使用a
在主要是错误的。如果您使用::a
,它将为您提供全局名称(没有名称空间)。
你可以在命名空间本身使用a
,例如我们可以有一个函数:
namespace {
int a;
int work_with_a()
{
a += 2;
return a;
}
}
int a;
int main()
{
::a++;
int b = work_with_a();
cout << ::a + b;
}
相关文章:
- 用C++中的一个变量定义一个常量
- 变量定义到C++布尔值转换
- 未声明的标识符错误,但变量定义正确 (?)
- C++多线程程序:变量定义为类成员的隔离错误
- 将变量定义为静态时,为什么可以多次定义它
- 初始值设定项列表与构造函数赋值与变量定义
- 如何根据传递给函数的变量定义特征矩阵大小
- C++ 描述如何使用来简化变量定义
- 如何转发声明依赖于变量定义的类,而变体定义又依赖于模板化类?
- 是否修改其声明语句中的变量定义良好
- 使用类的其他成员变量定义类的成员变量数组
- 是否可以通过全局变量定义具有可变参数数的函数中的参数数量
- 元组 std::get() 不适用于变量定义的常量
- 全局使用变量定义和C 声明
- C++变量定义中的易失性类型量词位置
- 将变量定义为数组和正确的语法
- 多个,包括具有变量定义的头文件
- 调用构造函数,并将成员作为参数解析为变量定义
- 逗号分隔变量定义中关系前的序列
- 如何使用命名变量定义常量右值引用参数的默认值