无法使用基类指针调用派生类函数 [英] Unable to call derived class function using base class pointers

查看:94
本文介绍了无法使用基类指针调用派生类函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用基类指针调用基类中未定义的派生类函数.但这总是会引发错误:

I want to call a derived class function that isn't defined in the base class using base class pointers. but this always raises the error:

error C2039: ‘derivedFunctionName’ : is not a member of ‘BaseClass’

你知道我该如何解决吗?

Do you know how I could get around this?

谢谢

推荐答案

不能通过指向基类的指针来调用仅出现在派生类中的成员.首先,必须将其强制转换(可能使用 dynamic_cast )到派生类型的指针,否则编译器甚至不知道该方法是否存在.

You can't call a member that appears only in a derived class through a pointer to the base class; you have to cast it (probably using dynamic_cast) to a pointer to the derived type, first -- otherwise the compiler has no idea the method even exists.

它可能看起来像这样:

void someMethod(Base* bp) {
    Derived *dp = dynamic_cast<Derived*>(bp);
    if (dp != null)
        dp->methodInDerivedClass();
}

这篇关于无法使用基类指针调用派生类函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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