如何通过基类指针调用派生类的虚函数

如何通过基类指针调用派生类的虚函数

问题描述:

让我们看看这段代码:

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.