首页 > 解决方案 > 我可以在 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编辑了。所以构造函数只能用于知道类型

标签: c++structlanguage-lawyertypedef

解决方案


例如这个 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 声明是有效的。


推荐阅读