我们来看看这段代码:
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;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
CBase::vfunc()
Run Code Online (Sandbox Code Playgroud)
但我想看看:CChild :: vfunc()
显式((CChild*)pBase)强制转换为"CChild*".那么为什么调用派生的vfunc()我需要用以下代码替换"important"字符串:((CChild*)pBase) - > CChild :: vfunc();