LoginSignup
0
0

More than 3 years have passed since last update.

多重継承のアップキャスト問題(C++)(未解決)

Posted at

手当たり次第にググっても希望の結果を見つけられなかったので、まずはメモとして残します。

多重継承するとアップキャストするときに途中の経路へキャストしなければならない

class I1  {};
class C1 : public I1  {};
class C2 : public I1  {};
class C12 : public C1, public C2  {};

int main()
{
    I1* ar[3];
    ar[0] = new C1;
    ar[1] = new C2;
    //ar[2] = new C12;  あいまいですエラー

    C12 c12;
    ar[2] = static_cast<C1*>(&c12);
}

これだとクラスを使う側がキャスト経路を意識する必要があります。
operator で解決しようと考えてもポインタとしてのキャストができません。

class C12 : public C1, public C2  {
public:
    operator I1*() { return static_cast<C1*>(this); }
};

int main()
{
    ...

    C12 c12;
    ar[2] = c12;
    ar[2] = *( new C12 );
    ar[2] = C12();
}

ポインタに実体を代入するというようなソースになるので気持ち悪いです。
キャストの経路をクラス提供側で解決する術は無いのでしょうか。
一般的には次の方法で解決します。

class I1  {};
class C1 : public virtual I1  {};
class C2 : public virtual I1  {};
class C12 : public C1, public C2  {};

int main()
{
    I1* ar[3];
    ar[0] = new C1;
    ar[1] = new C2;
    ar[2] = new C12;    // OK!
}

しかしこれは本質的な解決と言えない気がします。
キャストの経路を明示したのではなく経路をすっ飛ばすやり方です。
またI1の実体が2個から1個になるためC1,C2の実装に影響する恐れがあります。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0