为什么可以声明一个结构和非结构用相同的名字吗? [英] Why is it possible to declare a struct and a non-struct with the same name?
问题描述
显然,
对于伸入C的prehistory的原因,有可能宣布一个结构和非结构用在同一范围内的同一名称。 - ( Bjarne的Stroustrup的 - 在C ++语言程序设计第4版的)
For reasons that reach into the prehistory of C, it is possible to declare a struct and a non-struct with the same name in the same scope. - (Bjarne Stroustrup - The C++ Programming Language. 4th Edition)
例如:
struct Ambig {};
// the struct must be referred to with the prefix struct
void Ambig(struct Ambig* buf) {}
我只是好奇什么最初原因是?如果没有理解,就好像坏语言设计的例子,引起模糊和混乱。
I'm just curious what the initial reason was? Without understanding, it seems like an example of bad language design, that causes ambiguity and is confusing.
推荐答案
究其原因,在你的报价从Stroustrup的规定,是
历史的。在C语言中,你的必须的始终preFIX的名字
与结构
结构;该结构的名称(如名称
工会或枚举)被称为标记,住在一个完全
不同的名称空间比其他符号。所以这样的话:
The reason, as stated in your quote from Stroustrup, is
historical. In C, you must always prefix the name of the
struct with struct
; the name of the struct (like the name of
unions or enums) is called a tag, and lives in a completely
different name space than other symbols. So things like:
struct stat
{
// ...
};
int stat( char const* filename, struct stat* buf );
是完全合法的。 (以上是,事实上,Posix的的一部分)。
are perfectly legal. (The above is, in fact, part of Posix).
在C ++中,类名(含宣告类
,结构
或联盟
)或一个enum处于同一个命名空间一切,
而不像在C,你可以写的东西,如:
In C++, the name of a class (declared with class
, struct
or
union
) or an enum is in the same namespace as everything else,
and unlike in C, you can write things like:
struct MyClass {};
MyClass variableName;
此将不合法C.在C中,第二线必须是:
This would not be legal C. In C, the second line would have to be:
struct MyClass variableName;
的问题是,C ++需要能够使用接口
在C(如Posix接口的上面)定义。所以C ++定义
一些特殊的规则,以允许它:你可以给一个变量或
函数和类类型相同的名称。当你这样做时,
变量或函数名称具有precedence,并隐藏类
名,除了在详尽的类型说明符(即类
,结构
,联盟
或枚举
,后跟一个符号) ,其中
非类型名称在查找被忽略。
The problem is that C++ needs to be able to use interfaces
defined in C (like the Posix interface, above). So C++ defines
some special rules to allow it: you can give a variable or
a function and a class type the same name. When you do, the
variable or function name has precedence, and hides the class
name, except in "elaborated type specifiers" (i.e. class
,
struct
, union
or enum
, followed by a symbol), where
non-type names are ignored in the lookup.
这篇关于为什么可以声明一个结构和非结构用相同的名字吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!