简体   繁体   中英

How to make a struct of structs in C++

Can a struct contain other structs?

I would like to make a struct that holds an array of four other structs. Is this possible? What would the code look like?

Yes, you can. For example, this struct S2 contains an array of four S1 objects:

struct S1 { int a; };

struct S2
{
    S1 the_array[4];
};

Sure, why not.

struct foo {
    struct {
        int a;
        char *b;
    } bar[4];
} baz;

baz.bar[1].a = 5;

Yes, structs can contain other structs. For example:

struct sample {
  int i;
  char c;
};

struct b {
  struct sample first;
  struct sample second;
};

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