#includestdiohclass CParent public virtual void Intro printf Im a Parent ; Hobby; virtual void Hobby printf I like football! ; ; class CChild public CParent public v
这段代码定义了一个父类CParent和一个子类CChild,并且在主函数中创建了一个CChild对象pChild,并将其强制转换为CParent指针pParent。然后调用pParent的Intro()函数。
在CParent类中,Intro()函数首先输出"I'm a Parent, ",然后调用Hobby()函数输出"I like football!"。
在CChild类中,Intro()函数首先输出"I'm a Child, ",然后调用Hobby()函数输出"I like basketball!"。
由于pParent指针是指向CChild对象的,所以在调用pParent->Intro()时,实际上会调用CChild类中的Intro()函数。输出结果为"I'm a Child, I like basketball!"。
这段代码展示了虚函数的动态绑定效果,即在运行时根据对象的实际类型来确定调用的函数版本。
原文地址: https://www.cveoy.top/t/topic/iiHv 著作权归作者所有。请勿转载和采集!