【问题标题】:c++ using the child class methods of a class that inherits an interfacec++ 使用继承接口的类的子类方法
【发布时间】:2013-06-19 14:55:15
【问题描述】:

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

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

【问题讨论】:

  • 这可能是个坏主意——如果你希望能够通过接口调用方法,你应该将它添加到接口中。

标签: c++ inheritance interface


【解决方案1】:

你想要动态演员。

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

【讨论】:

    【解决方案2】:

    试试这样:

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

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

    【讨论】:

    • 如果您有 RTTI,按照 user814628 建议的方式操作会更安全。
    猜你喜欢
    • 1970-01-01
    • 2021-06-23
    • 1970-01-01
    • 1970-01-01
    • 2022-09-23
    • 2013-03-19
    • 2013-01-09
    • 1970-01-01
    • 2023-03-26
    相关资源
    最近更新 更多