c++ - 为什么在同一声明区域内的同名声明被拒绝?

标签 c++ language-lawyer

以下代码无法编译:

#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/

相关文章:

c++ - C/C++ 中的简单 OpenSSL RSA 加密让我头疼

C++ 结构继承

c++ - 调用函数时出错

c++ - C++ 中对不存在的对象进行赋值

c++ - I(I()) 的含义

c++ - if (condition) try {...} 在 C++ 中合法吗?

c++ - 在编译错误时制作 nvcc 输出跟踪

c++ - 在 g++ 中更改默认的 C++ 标准

c++ - 没有默认构造函数的值初始化

c++ - 这是未定义的行为还是 struct init 的错误?