如何在继承 class/struct 中添加联合成员

How to add union members in an inherited class/struct

struct Foo 
{
    union {
        struct { int a, b; };
        int index[2];
    };
};

struct Bar : public Foo 
{
    union {
        // Foo members
        struct { int barA, barB; };
    };

};

int main()
{
    Foo f;
    Bar b;
    // I want it so that
    &b.a == &b.barA;
    // in the same way that
    &f.a == &f.index[0];
}

有什么方法可以使 Bar 的成员 'union-ized' 与其父 class 一致?

非常感谢,非常感谢任何帮助

编辑: 这是请求的用例:

struct Vec2
{
    union {
        float index[2]; 
        struct { float x, y; };
    };

    Vec2(float xVal, float yVal)
        : x(xVal), y(yVal)
    {   
    }

    ~Vec2() {}

    Vec2 & add(const Vec2 & b) { /* implimentation */ }
    Vec2 & sub(const Vec2 & b) { /* implimentation */ }

};

struct ComplexNumber : public Vec2
{
    union {
        // Vec2 members
        struct { float real, imag; };
    };

    ComplexNumber(float realPart, float imagPart)
        : real(realPart), imag(imagPart)
    {
    }

    ComplexNumber & mul(const ComplexNumber & b) { /* implimentation */ }
    ComplexNumber & div(const ComplexNumber & b) { /* implimentation */ }
};

int main()
{
    ComplexNumber a(5, 2);
    ComplexNumber b(7, 8);
}

我希望不仅能够解决 a 和 b 的 Vec2 成员, 但也可以使用 Vec2 中声明的函数,甚至可能添加 ComplexNumbers 和 Vec2s 可互换。

您在 FooBar 中的工会是匿名工会。这是语法糖,允许访问它们的成员,就好像它们在封闭的 class:

中一样

[class.union.anon]/1:

For the purpose of name lookup, after the anonymous union definition, the members of the anonymous union are considered to have been defined in the scope in which the anonymous union is declared.

但这只是会员访问的便利。匿名联合对象未合并到其封闭 class 中。因此,在 Bar 中有两个不同的联合(对象在不同的​​地址)。这些不能是 unionized/merged。

顺便说一下,标准明确禁止联合以任何方式继承:

[class.union]/3:

A union shall not have base classes. A union shall not be used as a base class.

没有办法做你想做的事。

根据您的具体情况,您希望在派生 class 中建立的合并联合似乎与基础 class 的部分具有一对一的关系。鉴于这些情况,您可以 解决方法 使用一些引用来引用同一成员:

struct ComplexNumber : public Vec2
{
    float &real=x, &imag=y;

    ComplexNumber(float realPart, float imagPart) : Vec2 (realPart, imagPart)
    {
    }
    ...
 }; 

当然,您需要实施规则 3,以避免任何问题(例如,引用指向错误的对象,以防复制构造函数或赋值完成)。

现在真正的问题是复形是否是 Vec2。就个人而言,我宁愿采用更清晰的方法,使复合体成为独立的 class 并拥有一个 Vec2 成员。在这种情况下,复合体将重新定义 Vec2 操作并将成员函数转发给 Vec2 成员。