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_case
或lowerCamelCase
(有时称为mixedCase
)名称。
您可以使用Typedef暂时别名。
class a;
typedef a _a;
_a a;
void Get(_a a);
相关文章:
- 什么时候调用组成单元对象的析构函数
- 对RValue对象调用的LValue ref限定成员函数
- CMake-按正确顺序将项目与C运行时对象文件链接
- 空基优化子对象的地址
- 将对象数组的引用传递给函数
- 你能重载对象变量名本身返回的内容吗
- C++使用整数的压缩数组初始化对象
- 找不到成员对象:没有名为get_event()的成员,也处理多态性和向量
- 将对象移动到std::shared_ptr
- 代理对象的常量正确性
- 提升 ASIO 无法识别计时器对象
- 将Ref对象作为类成员
- 将包含C样式数组的对象初始化为成员变量(C++)
- 如何返回一个类的两个对象相加的结果
- 使用std::函数映射对象方法
- 是否需要删除包含对象的"pair"?
- 如何在自删除后将对象设置为nullptr
- 迭代时从向量和内存中删除对象
- 构造对象的歧义
- 使用"std::unordereded_map"映射到"std::list"对象