1

ユニオンから次の動作を取得することは可能ですか?

class A : public Base //Base is an abstract base class.
{
  public:
    A( int );
    virtual void foo() //A virtual function from Base.
    {
      //I don't want to have to specify if it's oneOption or twoOption.
      // I would like it to just call whichever one's is defined in mData.
      mData.foo();
    }
  private:
    union B
    {
      C oneOption; //A class which inherits from Base.
      D twoOption; //Another class which inherits from Base.
    } mData;
};

基本的に、派生クラスのユニオンを含むクラスが必要です。次に、Union に関してすべての仮想関数の基本クラスを実装したいと思います。

あまりにも紛らわしい場合は、これを言い換えてみることができます。

ありがとう

4

2 に答える 2

2

共用体のメンバーは、コンストラクターを持つことができません。

次のようなことができます。

void PickC() { new (oneOption) C; }
void PickD() { new (twoOption) D; }
C * GetC() { return (C*) oneOption; }
D * GetD() { return (D*) twoOption; }

private:

union B
{
  char oneOption[ sizeof(C) ]; //A class which inherits from Base.
  char twoOption[ sizeof(D) ]; //Another class which inherits from Base.
} mData;

しかし、それはひどく醜いです。

于 2013-04-12T02:17:59.907 に答える