Accessing child variables through higher level structures

后端 未结 8 1768
孤街浪徒
孤街浪徒 2020-12-09 17:41

If I have these structures:

typedef struct { int x; } foo;
typedef struct { foo f; } bar;

Normally you would access x through

相关标签:
8条回答
  • 2020-12-09 18:09

    In C++, it is possible in two ways. The first is to use inheritence. The second is for bar to contain a reference member named x (int &x), and constructors that initialise x to refer to f.x.

    In C, it is not possible.

    0 讨论(0)
  • 2020-12-09 18:13

    In C (99 and onward) you can access the common initial sub-sequence of union members, even if they weren't the last member written to1.

    In C11, you can have anonymous union members. So:

    typedef struct { int x; } foo;
    typedef struct {
      union {
        foo f;
        int x;
      };
    } bar;
    

    1. Yes, that applies to structures. But according to the standard:
      • A structure pointer, suitably converted, points to the first member.
      • A union pointer, suitably converted, points to any union member.
      • So their location in memory is the same.
    0 讨论(0)
提交回复
热议问题