如何通过基类指针调用派生类的虚函数 [英] How to call virtual function of derived class through base class pointer

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

问题描述

让我们看看这段代码:

class CBase
{
 public:
    virtual vfunc() { cout << "CBase::vfunc()" << endl; }
};

class CChild: public CBase
{
 public:
    vfunc() { cout << "CChild::vfunc()" << endl; }
};

int main() 
{
 CBase *pBase = new CBase;
 ((CChild*)pBase)->vfunc(); // !!! important 
 delete pBase;
 return 0;
}

输出为:

CBase::vfunc()

但我想要看:CChild :: vfunc()

But I want to see: CChild::vfunc()

显式((CChild *)pBase)强制转换为CChild *。那么为什么调用派生的vfunc()我需要用以下代码替换重要字符串:
((CChild *)pBase) - > CChild :: vfunc();

Explicit ((CChild*)pBase) casts to type "CChild*". So why to call derived vfunc() I need replace "important" string with: ((CChild*)pBase)->CChild::vfunc();

推荐答案

这不是它的工作原理 - 这是:

That's not how it works - this is:

CBase *pBase = new CChild;
pBase->vfunc();

虚拟函数调用在指针上动态解析&安培;引用(除非您明确地调用该方法,就像您所做的那样)。这意味着你告诉编译器指针是什么并不重要,它将在vftable中查找方法。在您的情况下, vftable CBase

virtual function calls are resolved dynamically on pointers & references (unless you call the method explicitly, like you did). Which means it doesn't matter what you tell the compiler the pointer is, it will look for the method in the vftable. Which, in your case, is the vftable of CBase.

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

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