c++ - 我可以在 C++ 中 typedef 未命名的结构/类吗?
问题描述
在 C 中,我可以 typedef 未命名(无标签)结构:
typedef struct {
int val;
} Foo_t;
但是当我尝试在 C++ 中做同样的事情时:
typedef struct
{
A(int a) : a_var(a) {}
int a_var;
} A;
typedef struct : public A
{
B(int a, int b) : A(a), b_var(b) {}
int b_var;
} B;
B &getB()
{
static B b(1, 2);
return b;
}
int main() {}
输出:
error: ISO C++ forbids declaration of ‘A’ with no type
error: only constructors take member initializers
error: class ‘<unnamed struct>’ does not have any field named ‘A’
我知道我正在使用A(int a)
“未命名”结构的构造函数,但在它之后,它被typedef
编辑了。所以构造函数只能用于知道类型
解决方案
例如这个 typedef 声明的问题
typedef struct
{
A(int a) : a_var(a) {}
int a_var;
} A;
是在未命名的结构中使用未声明的名称 A 作为构造函数的名称。所以这个声明是无效的。
顺便说一句,C 中的其他地方也存在同样的问题。
例如,考虑用于定义链表节点的结构的 typedef 声明。
typedef struct
{
int data;
A *next;
} A;
同样,A
结构定义中的名称是未定义的。
即使你会这样写
typedef struct A
{
int data;
A *next;
} A;
尽管如此,该名称A
仍未在 C 的结构中声明。您必须用 C 编写
typedef struct A
{
int data;
struct A *next;
} A;
另一方面,在 C++ 中,这样的 typedef 声明是有效的。
推荐阅读
- angular - 如何在 Angular 库中添加引导程序
- c# - ASP.net Core MVC 登录
- python - 使用矢量化操作将不同维度的 rank-2 Numpy 数组与自定义函数相结合
- python - Print Circle - 迭代中的解决方案
- swift - 具有自动单元格大小的水平集合视图正在破坏项目重新加载时的单元格
- javascript - 从对象数组中查找最接近给定日期的日期
- c# - 如何使用 Microsoft Exchange WebServices 搜索特定邮箱?
- vba - 合并字段上的条件格式 - 它只是将代码打印到输出而不是渲染
- php - MariaDB 在使用加载数据本地 infile 时会跳过一些自动递增值
- ios - 删除 Fabric 导致 NSInvalidArgumentException