0

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

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

2 回答 2

4

你想要动态演员表。

ChildClass * child = dynamic_cast<ChildClass*>(aClient);
if(child){ //cast sucess
  child->anotherMethod();
}else{
  //cast failed, wrong type
}
于 2013-06-19T14:58:17.280 回答
0

试试这样:

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

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

于 2013-06-19T14:59:30.073 回答