C ++对象名称与类名称相同 [英] C++ object name same as class name

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

问题描述

我碰巧写了这样的代码:

I happen to write a code like this:

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 ++很高兴,这是好的代码:

I found that, if I change "a *a" to "a *b" at line 10, then g++ is happy, here is the good code:

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


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

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

I am confused, not sure why the original code does not compile and how the "fix" works.

有什么主意吗?

推荐答案

有关详细信息,请参见沃恩的答案.但是,如果您指定要使用 class 而不是变量,则可以解决此问题:

See Vaughn's answer for details. However, you can fix this problem if you specify that you want to use the class and not the variable:

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 ++中,发生了类似的事情,但是,只要不存在具有相同名称的局部函数或变量,类名称就可以在其名称空间之外使用.

Explanation

Back in the days of C structs were put in their own namespace. In C++ something similar happens, however, the class names are available outside of their namespace, as long as there is no local function or variable with the same name.

如果碰巧对类/结构 A 和变量/函数 A 使用相同的名称,则必须使用 struct / class 关键字,因为编译器会将 A 的所有后续出现解释为变量/函数,而不是struct/class.

If you happen to use the same name for both a class/struct A and a variable/function A you have to use the struct/class keyword, because the compiler interprets all following occurrences of A as the variable/function and not the struct/class.

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

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