C 对象名称与类名称相同

C++ object name same as class name

本文关键字:对象      更新时间:2023-10-16

我碰巧写这样的代码:

class a
{
    public:
        a() {}
};

int main()
{
    a *a = new a;        // line 10
    a a;                 // line 11
    return 0;
}

g 错误:

2.c: In function ‘int main()’:
2.c:10:16: error: expected type-specifier before ‘a’
2.c:10:16: error: cannot convert ‘int*’ to ‘a*’ in initialization
2.c:10:16: error: expected ‘,’ or ‘;’ before ‘a’
2.c:11:7: error: expected ‘;’ before ‘a’

我发现,如果我在第10行中将" A *a"更改为" A *B",那么G 很高兴,这是很好的代码:

class a
{
    public:
        a() {}
};

int main()
{
    a *b = new a;
    a a;
    return 0;
}

我很困惑,不确定为什么原始代码不编译以及"修复"如何工作。

有什么想法?

有关详细信息,请参见Vaughn的答案。但是,如果指定要使用 class 而不是变量:

,则可以解决此问题
class a
{
    public:
        a() {}
};

int main()
{
    a *a = new class a;
    return 0;
}

int main()
{
    class a a; // although the class word isn't needed here
    return 0;
}

说明

回到C结构的时代被放置在自己的名称空间中。但是,在C 中发生了类似的事情,但是,只要没有具有相同名称的本地函数或变量,则可以在其命名空间之外提供类名称。

如果您碰巧使用类/struct A和变量/函数A同时使用相同名称,则必须使用struct/class关键字,因为编译器将A的所有以下内容解释为可变/函数结构/班级。

一旦看到了您要声明的变量名称,就可以访问。

所以在此代码中:

a *a = new a;
           1

在第1点,a指的是变量A,而不是类A。

当您这样做时:

a *b = new a;
a a;

这不是问题,因为b是一个不同的名称。

g 找到标识符a,并认为您是指指针,而不是类名。您行 a *a = new a;与:

相同
a *a;
a = new a;

在第二行中,G 感到困惑,因为您已经将a定义为指针,而不是类名称。

另一行a a;起作用,因为它只是一个语句。

通常是一个好主意,最好给您的类CamelCase(每个单词的拳头字母上的命名)名称,并且实例(可变名称)lower_caselowerCamelCase(有时称为mixedCase)名称。

您可以使用Typedef暂时别名。

class a;
typedef a _a;
_a a;
void Get(_a a);