Why does declaration of the same name inside the same declarative region is denied?

此生再无相见时 提交于 2019-12-24 13:16:33

问题


The following code does not compile:

#include <iostream>
#include <stdio.h>

int a=5;
char a='a';

int main(){ std::cout << a;}

It is because:

test.cpp:5:6: error: conflicting declaration ‘char a’
test.cpp:4:5: error: ‘a’ has a previous declaration as ‘int a’

But where does this restriction specified in the standard? I can't find it. Please give me a reference.


回答1:


This is a simple violation of the One Definition Rule (ODR). See n3797 S3.2/1.

No translation unit shall contain more than one definition of any variable, function, class type, enumeration type, or template.

There really is no more to be said. Each of those lines is a definition of a (not a declaration). The program is ill-formed.

If these declarations were in different translation units the program would still be ill-formed, but the applicable rule is different. See S3.5/10.




回答2:


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 ]

Neither of these conditions is met in your case, so your program is ill-formed.




回答3:


The actual reason in the current case is ODR as rightly observed by david.pfx. But consider the following example:

#include <iostream>
#include <stdio.h>

extern int a;
extern char a;

int main(){ std::cout << a;}

The actual reason is not the violation of 3.3. Actually in the 13/1 said:

When two or more different declarations are specified for a single name in the same scope, that name is said to be overloaded. By extension, two declarations in the same scope that declare the same name but with different types are called overloaded declarations. Only function and function template declarations can be overloaded; variable and type declarations cannot be overloaded.

Hence, I'm just trying to overload non-function declaration.



来源:https://stackoverflow.com/questions/23973281/why-does-declaration-of-the-same-name-inside-the-same-declarative-region-is-deni

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!