有这样的代码:定义
int x;
//void x(); // error: redefinition of 'x' as different kind of symbol
class x {}; // works ok
int main() {
return 0;
}
为什么法律定义的变量和类具有相同的名称,但它是不合法的定义变量和函数具有相同名称?
有这样的代码:定义
int x;
//void x(); // error: redefinition of 'x' as different kind of symbol
class x {}; // works ok
int main() {
return 0;
}
为什么法律定义的变量和类具有相同的名称,但它是不合法的定义变量和函数具有相同名称?
这里发生的事情是特定于C++的。使用x
作为类名是隐藏的。
第3.3.7节(名字隐藏)第2段:
类名(9.1)或枚举名称(7.2)可通过一个对象,功能的名称被隐藏,或枚举在宣布同样的范围。如果类或枚举名称和对象,函数或枚举器在相同的作用域(以任何顺序)中声明具有相同的名称,则无论对象,函数或枚举器名称是否可见,都将隐藏类或枚举名称。
第一种情况: 2标识符
int x;
void x();
第二种情况: 1标识符,1类型名
int x;
class x {};
编译器,因为你有2名标识符与不能处理的第一例同名,所以可能会有歧义。 (例如:尝试获取其中一个的内存地址,这是一种可能出现歧义的情况)
编译器可以处理第二种情况,因为一种是类型,另一种是标识符,并且因为它知道在哪里期望一个类型和在哪里期待一个标识符,这是没有歧义的。
union
,enum
和struct
(我想class
太)共同拥有单独的“名桶”(无关与C++命名空间!)从普通的标识符。这一点在清除C,因为你有struct
等
前缀的名字,我没有它C++,但是这是从C标准:
6.2.3 Name spaces of identifiers
If more than one declaration of a particular identifier is visible at
any point in a translation unit, the syntactic context disambiguates uses
that refer to different entities.
Thus, there are separate name spaces for various categories of identifiers,
as follows:
— label names (disambiguated by the syntax of the label declaration and use);
— the tags of structures, unions, and enumerations (disambiguated by
following any32) of the keywords struct, union, or enum);
— the members of structures or unions; each structure or union has a
separate name space for its members (disambiguated by the type of the
expression used to access themember via the . or -> operator);
— all other identifiers, called ordinary identifiers (declared in ordinary
declarators or as enumeration constants).
这是完全错误的。 C++中唯一的“名称空间”是使用关键字'namespace'(或全局名称空间)的defiend。这是C和C++完全不同的一种情况。 –
这不应该是选定的答案。这对于C++来说是100%错误的,而且这个问题只被标记为C++。 –
@JamesKanze DavidHammen我知道,“命名空间”是错误的词,但我应该怎么称呼它呢?请备份你的声明,这些消歧规则对于C++来说是完全错误的。 – typ1232
这是需要向后与C兼容(如果我记得,一些UNIX头文件同时定义了一个结构和一个变量)。
您可以在类和变量/函数间的歧义:
int x;
class x {};
int main()
{
x = 42; // global int x
//x obj; // error
class x obj; // use class-tag to disambiguate
}
但你不能变量和函数间的歧义。
另请参阅书籍“The Design and Evolution of C++” by Bjarne Stroustrup,§2.8.2。
你对函数变量对有什么建议'&x'? – chris