如何从父指针调用子方法? [英] How to call child method from a parent pointer?

查看:41
本文介绍了如何从父指针调用子方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a base class and a child class extending it. The child class has its own method inside that the parent class does not have. That is, declaring it as virtual in the base class is not really an option.

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

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

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

Then, in my implementation, I have a pointer to A and I constructed it as B:

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

我当前的解决方案是投射它:

My current solution is to cast it:

((B *)x)->myNewMethod();

我的问题是,是否有更清洁的方法来实现这一目标?

My question is, is there a cleaner way of doing this, or is casting the way to go?

推荐答案

我的问题是,是否有更清洁的方法来实现这一目标?

My question is, is there a cleaner way of doing this, or is casting the way to go?

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

A run-time cast seems to be OK in this case. However, rather than C-style casts, you should use dynamic_cast<> (in case you are not sure whether x actually points to an object of type of B):

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();
}

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

On the other hand, if you are sure that x points to an object of type B, then you should use static_cast<>:

B* pB = static_cast<B*>(x);
pB->myNewMethod();

这篇关于如何从父指针调用子方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆