簡體   English   中英

如何在繼承的類/結構中添加聯合成員

[英]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 的成員與其父類“聯合化”?

非常感謝,非常感謝任何幫助

編輯:這是要求的用例:

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.union.anon]/1:

出於名稱查找的目的,在匿名聯合定義之后,匿名聯合的成員被認為已在聲明匿名聯合的范圍內定義。

但這只是促進成員訪問。 匿名聯合對象未合並到其封閉類中。 因此,在Bar有兩個不同的聯合(對象位於不同的地址)。 這些不能被工會化/合並。

順便說一下,標准明確禁止 union 以任何方式繼承:

[class.union]/3:

聯合不應有基類。 聯合不應用作基類。

沒有辦法做你想做的事。

看看你的具體情況,你想在派生類中建立的合並聯合似乎與基類的部分有一對一的關系。 鑒於這些情況,您可以作為一種解決方法,使用一些引用來引用同一個成員:

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

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

當然,您需要實現 3 規則,以避免出現任何問題(例如,引用指向錯誤的對象,以防復制構造函數或賦值完成)。

現在真正的問題是復合體是否是 Vec2。 就個人而言,我更願意采用更清晰的方法,使復雜的成為獨立的類並擁有一個 Vec2 成員。 在這種情況下,復合體將重新定義 Vec2 操作並將成員函數轉發給 Vec2 成員。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM