2013-06-19 47 views
0

我想從一個繼承自接口的類的子類使用方法。從客戶類(main方法)調用該方法。 //接口方法C++使用繼承接口的類的子類方法

class InterfaceMethod{ 
    virtual void method(void) = 0; 
} 

這是繼承接口的類:

class ChildClass: public InterfaceMethod 
{ 
    public: 
    ChildClass(){} 
    ~ ChildClass(){} 
    //virtual method implementation 
    void method(void) 
{ 
//do stuff 
} 
//and this is the method that i want to use! 
//a method declared in the child class 
void anotherMethod() 
{ 
    //Do another stuff 
} 
private: 

} 

這是客戶:

int main() 
{ 
    InterfaceMethod * aClient= new ChildClass; 
    //tryng to access the child method 

    (ChildClass)(*aClient).anotherMethod();//This is nor allowed by the compiler!!! 
} 
+0

這可能是一個壞主意 - 如果您希望能夠通過接口調用該方法,則應將其添加到接口中。 – doctorlove

回答

4

你要動態轉換。

ChildClass * child = dynamic_cast<ChildClass*>(aClient); 
if(child){ //cast sucess 
    child->anotherMethod(); 
}else{ 
    //cast failed, wrong type 
} 
0

試試這樣說:

static_cast<ChildClass*>(aClient)->anotherMethod(); 

你不應該這樣做,除非你能確保你有派生類的一個實例。

+0

如果你有RTTI,按照user814628建議的方式進行操作會更安全。 – TractorPulledPork