gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:58:07 25 4
gpt4 key购买 nike

让我们看看这段代码:

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

显式 ((CChild*)pBase) 转换为类型“CChild*”。那么为什么要调用派生的 vfunc() 我需要将“重要”字符串替换为: ((CChild*)pBase)->CChild::vfunc();

最佳答案

这不是它的工作方式 - 这是:

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

virtual 函数调用在指针和引用上动态解析(除非您像以前那样显式调用该方法)。这意味着无论您告诉编译器指针是什么,它都会在 vftable 中查找方法。在您的例子中,它是 CBasevftable

关于c++ - 如何通过基类指针调用派生类的虚函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11907507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com