以下代码无法编译:
#include <iostream>
#include <stdio.h>
int a=5;
char a='a';
int main(){ std::cout << a;}
这是因为:
test.cpp:5:6: error: conflicting declaration ‘char a’
test.cpp:4:5: error: ‘a’ has a previous declaration as ‘int a’
但是这个限制规定在标准的什么地方呢?我找不到它。请给我一个引用。
最佳答案
C++11 §3.3.1 ¶4
Given a set of declarations in a single declarative region, each of which specifies the same unqualified name,
- they shall all refer to the same entity, or all refer to functions and function templates; or
- exactly one declaration shall declare a class name or enumeration name that is not a typedef name and the other declarations shall all refer to the same variable or enumerator, or all refer to functions and function templates; in this case the class name or enumeration name is hidden (3.3.10). [ Note: A namespace name or a class template name must be unique in its declarative region (7.3.2, Clause 14). — end note ]
您的情况都不满足这些条件,因此您的程序格式错误。
关于c++ - 为什么在同一声明区域内的同名声明被拒绝?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23973281/