如何从c ++中的父指针调用子方法?

Sef*_*efu 11 c++ polymorphism inheritance

我有一个基类和一个扩展它的子类.子类在父类中没有自己的方法.也就是说,在基类中将其声明为虚拟实际上并不是一种选择.

class A {
  public:
    virtual void helloWorld();
};

class B : public A {
  public:
    virtual void helloWorld();
    void myNewMethod();
};
Run Code Online (Sandbox Code Playgroud)

然后,在我的实现中,我有一个指向A的指针,我将其构造为B:

// somewhere in a .cpp file
A* x;
x = new B();
x->myNewMethod(); // doesn't work
Run Code Online (Sandbox Code Playgroud)

我目前的解决方案是施展它:

((B *)x)->myNewMethod();
Run Code Online (Sandbox Code Playgroud)

我的问题是,是否有一种更清洁的方式来做到这一点,或者正在推行方式?

And*_*owl 14

我的问题是,是否有一种更清洁的方式来做到这一点,或者正在推行方式?

在这种情况下,运行时转换似乎没问题.但是,您应该使用dynamic_cast<>(如果您不确定是否x实际指向类型为的对象B),而不是C风格的强制转换:

B* pB = dynamic_cast<B*>(x); // This will return nullptr if x does not point
                             // to an object of type B
if (pB != nullptr)
{
    pB->myNewMethod();
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您确定x指向类型的对象B,那么您应该使用static_cast<>:

B* pB = static_cast<B*>(x);
pB->myNewMethod();
Run Code Online (Sandbox Code Playgroud)