2011-01-16 14 views
0

私は純粋な仮想メソッドを持つクラスのインターフェイスを持っています。別のクラスでは、Interfaceから継承したネストされた型を持ち、それを抽象化しません。私は型としてインターフェイスを使用し、型を初期化するために関数を使用しますが、私は取得している、抽象型のためにコンパイルできません。C++抽象型の初期化

インタフェース:

struct Interface 
{ 
    virtual void something() = 0; 
} 

実装:

class AnotherClass 
{ 
    struct DeriveInterface : public Interface 
    { 
     void something() {} 
    } 

    Interface interface() const 
    { 
     DeriveInterface i; 
     return i; 
    } 
} 

使用法:

struct Usage : public AnotherClass 
{ 
    void called() 
    { 
     Interface i = interface(); //causes error 
    } 
} 

答えて

4

あなたは

class AnotherClass 
{ 
    struct DeriveInterface : public Interface 
    { 
     void something() {} 
    } 

    DeriveInterface m_intf; 

    Interface &interface() const 
    { 
     return m_intf; 
    } 
} 

struct Usage : public AnotherClass 
{ 
    void called() 
    { 
     Interface &i = interface(); 
    } 
} 

プラスセミコロンのカップルを行うだろうし、それが正常に動作しますので、あなたは、ポインタや参照として抽象クラスを使用します。ポインタと参照のみがC++では多態的であることに注意してください。したがって、Interfaceが抽象型でなくても、いわゆるスライシングのためにコードが不正確になります。

struct Base { virtual int f(); } 
struct Der: public Base { 
    int f(); // override 
}; 

... 
Der d; 
Base b=d; // this object will only have B's behaviour, b.f() would not call Der::f 
0

あなたがここに*インターフェイスで作業する必要があります。