定义具有相同名称的类和变量 [英] Definition of class and variable with the same name

查看:167
本文介绍了定义具有相同名称的类和变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有以下代码:

int x;

//void x(); // error: redefinition of 'x' as different kind of symbol

class x {}; // works ok

int main() {
   return 0;
}

为什么用同样的名称定义变量和类是合法的不合法定义变量和函数具有相同的名称?

Why is it legal to define variable and class with the same name but it is not legal to define variable and function with the same name?

推荐答案

这里发生的是特定于C ++。 x 作为类名的使用被隐藏。

What's going on here is specific to C++. The use of x as a class name is hidden.

第3.3.7节


类名称(9.1)或枚举名称(7.2)可以通过在对象,函数或枚举器的名称相同的范围。如果类或枚举名称以及对象,函数或枚举器在同一范围(以任何顺序)中声明具有相同的名称,那么类或枚举名称在对象,函数或枚举器名称可见的地方都是隐藏的。 / p>

A class name (9.1) or enumeration name (7.2) can be hidden by the name of an object, function, or enumerator declared in the same scope. If a class or enumeration name and an object, function, or enumerator are declared in the same scope (in any order) with the same name, the class or enumeration name is hidden wherever the object, function, or enumerator name is visible.

这篇关于定义具有相同名称的类和变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆