c ++使用继承接口的类的子类方法

时间:2013-06-19 14:55:16

标签: c++ inheritance interface

我正在尝试使用从接口继承的类的子方法。从客户端类(main方法)调用该方法。 //接口方法

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!!!
}

2 个答案:

答案 0 :(得分:4)

你想要动态演员。

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

答案 1 :(得分:0)

试试这样:

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

除非您确定拥有派生类的实例,否则不应该这样做。