我可以在c ++中键入未命名的struct / class的名称吗?

问题描述

在C语言中,我可以输入typedef unnamed(无标签)结构:

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;

尽管如此,在C中的结构中仍未声明名称A。您必须在C中编写

typedef struct A
{
    int data;
    struct A *next;
} A;

另一方面,在C ++中,这样的typedef声明是有效的。

,

是的,可以,但是不能像您所说的那样在结构中使用类型名称。

// this is valid
typedef struct{
   int x;
   void set(int n){x=n;}
} A;

// this is not
typedef struct{
    int x;
    B(int n){x = n;}
} B;

// you can only have constructor with named structs
typedef struct st_C{
    int x;
    st_C(int n){x = n;}
} C;

// this is valid
C *foo = new C(3); 
,

在C语言中,您通常必须这样编写typdef:

typedef struct {
 int val;
} Foo_t;

避免写

struct Foo_t f;

每次,很快就会变得很乏味。

在C ++中,所有structunionenum的声明就像是暗含的 typedef。因此,您可以这样声明一个结构:

struct A
{
    A(int a) : a_var(a) {}
    int a_var;
};

但是,C ++中的结构通常是聚合(简单的数据集合),并且不需要构造函数。因此,以下情况很好:

struct A
{
    int a_var;
    int b_var;
};

构造函数由编译器隐式定义,并且当您将 value初始化与花括号一起使用时:

A a{};

该结构的所有成员将被清零。