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

c++ using the child class methods of a class that inherits an interface

本文关键字:类方法 接口 继承      更新时间:2023-10-16

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

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

你想要动态强制转换

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

试一下:

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

你不应该这样做,除非你能确定你有一个派生类的实例。