2012-04-20 13 views
2

私は、個人的なプロジェクトでフレームワークのさまざまなコンポーネントのインターフェイスを設定しています。私は突然、インターフェイスで役に立つかもしれないものを考えました。私の質問はこれが可能であるかどうかです:あなたはこのような何かを行うことができるかもしれないように、派生オブジェクト内で定義する必要がある仮想クラスまたは純粋仮想クラスを宣言するクラス内に仮想クラス宣言を入れることは可能ですか?

class a 
{ 
public: 
    virtual class test = 0; 

}; 

class b : public a 
{ 
public: 
    class test 
    { 
     public: 
      int imember; 
    }; 
}; 

class c : public a 
{ 
public: 
    class test 
    { 
    public: 
      char cmember; // just a different version of the class. within this class 
    }; 
}; 

ソート、 :

int main() 
{ 
    a * meh = new b(); 
    a * teh = new c(); 

    /* these would be two different objects, but have the same name, and still be able 
to be referred to by an interface pointer in the same way.*/ 
    meh::test object1;  
    teh::test object2; 

    delete meh; 
    delete teh; 

    return 0; 
} 

MSVC++は私に構文エラーの束を投げるので、これを行う方法があり、私はちょうどそれが右に書いていませんよ?

+0

あなたはおそらく*抽象クラスを使用してこれを達成することができます* –

+0

は何でもそれは、上記のコードであることは解決策ではありませんので、あなたの本当の問題は何XYの問題のような音 – MSalters

答えて

6

いいえ、無効です。いずれにしても、C++には仮想クラスの概念がありません。 (それは必須ではありませんが)あなたはおそらく唯一の純粋仮想メソッドで特定のクラスへのポインタを保持することによって、あなたが望むものを達成することができます:

class ITest { /* full of pure virtual methods... maybe. */}; 

class a 
{ 
public: 
    virtual ITest* someFunctionName()=0 ; 
private: 
    ITest* test_; 
}; 

次に、各実装コンクリートを与えて、継承することを決定することができますITestの実装、またはいくつかのコンストラクタパラメータに基づいてどのインプリメンテーションを使用するかを決定するなどの他の方法があります。

+0

失望が続きます...。しかし、提案に感謝します。私が取り組んでいることは、これを取得するだけで十分にmplicated:/。私は仮想クラスとは異なる方法を見つけることができると確信しています。誰もがなぜこれが機能ではないか知っていますか? – FatalCatharsis

+0

@FatalCatharsis:大まかに言えば、 '::'スコープ演算子は左のクラス(または名前空間)をとり、 '.'演算子は左辺の値(オブジェクト、参照、式など)をとります。 'meh :: test'はポインタ' meh'に '::'を適用します。また、C++は強く型付けされています。式 'meh :: test'の静的型はコンパイル時に設定されなければならないでしょう。潜在的にそれから派生したダイナミックなタイプを持つことができます、Liskov Substitutionはそれを可能にしますが、そのメカニズムは完全には不明です。 – MSalters

0

キーワード「仮想」は単なる関数呼び出しをディスパッチする」テーブルを意味します。 何を提案することは、言語の一部ではありません。

しかし、あなたは適切な仮想へのオブジェクトの生成を連鎖によって、別の方法でそれに近づくことができます通話:?。

#include <iostream> 

using namespace std; 


class a 
{ 
public: 
    class test 
    { 
    public: 
     virtual ~test() {} ///< required to have polimorphic behavior 
     virtual void hello() const =0; 
    }; 

    virtual test* create_test()=0; 
}; 


class b: public a 
{ 
public: 
    class test_b: public a::test 
    { 
     virtual void hello() const 
     { cout << "this is test_b at " << this << endl; } 
    }; 
    virtual test* create_test() 
    { return new test_b; } 
}; 

class c: public a 
{ 
public: 
    class test_c: public a::test 
    { 
     virtual void hello() const 
     { cout << "this is test_c at " << this << endl; } 
    }; 
    virtual test* create_test() 
    { return new test_c; } 
}; 

int main() 
{ 
    a* pa1 = new b; 
    a* pa2 = new c; 

    a::test* p1 = pa1->create_test(); 
    a::test* p2 = pa2->create_test(); 

    p1->hello(); 
    p2->hello(); 

    delete p2; delete p1; 
    delete pa2; delete pa1; 
}