简体   繁体   中英

Can I typedef unnamed struct/class in c++?

In C, I can typedef unnamed (no tag) struct:

typedef struct {
 int val;
} Foo_t;

But when I tried to do the same in 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() {}

output :

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’

I know I am using constructor A(int a) of "unnamed" struct, but right after it, it is typedef ed. So constructors are only available to know types

The problem for example with this typedef declaration

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

is that within the unnamed structure there is used undeclared name A as a name of a constructor. So this declaration is invalid.

By the way the same problem exists else in C.

Consider for example a typedef declaration of a structure used to define a node of a linked list.

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

Again the name A within the structure definition is undefined.

Even if you will write like

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

nevertheless the name A is still undeclared within the structure in C. You have to write in C

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

On the other hand, in C++ such a typedef declaration is valid.

Yes, you can, but it's not possible to make use of the type name inside the structure, as you said.

// 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); 

In C, you often have to write typdefs like this:

typedef struct {
 int val;
} Foo_t;

to avoid having to write

struct Foo_t f;

every time, which soon becomes quite tedious.

In C++, all struct s union s and enum s declarations act as though they are implicitly typedef ed. So you can declare a struct like this:

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

However, structs in C++ are often aggregates (a simple collection of data), and you don't need the constructors. So the following is fine:

struct A
{
    int a_var;
    int b_var;
};

The constructor is implicitly defined by the compiler, and when you use value initialisation with braces:

A a{};

all the members of the struct will be zeroed out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM