使用继承接口的类的子类方法
c++ using the child class methods of a class that inherits an interface
我正在尝试使用从接口继承的子类的方法。从客户端类(主方法)调用该方法。//接口方法
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();
你不应该这样做,除非你能确定你有一个派生类的实例。
相关文章:
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 在静态库中嵌入类方法
- 如何制作一个将函数作为参数的类方法
- 从父类方法返回子类对象
- 使用用户定义的参数调用future/async并调用类方法
- 重载类方法的不明确调用
- 单独定义模板化嵌套类方法的正确语法
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何访问由共享指针保存的类方法?
- 将子类方法声明为基类的友元
- 我的模板类方法返回错误类型?
- Qt将信号与另一个类方法连接
- 我无法使用C++指针指向类方法返回的 std::vector
- 如何在成为指向基类的指针后保留对子类方法的使用?
- 检查类方法中是否(此 == nullptr)
- C ++类实现接口,接口具有采用任何实现该接口的类的方法
- 通过抽象模板基类接口指针访问派生类方法,而无需在接口中显式类型
- 基类方法的接口
- 使用继承接口的类的子类方法
- 如何在c++ Builder中解决接口方法和基类方法名称冲突?