C++ 虚函数与多态性示例:详解运行结果及问题分析
#include
}; class B :public A { public: void hello() { cout << 'B::hello' << endl; } virtual void func() { cout << 'B::func' << endl; } }; int main() { B* pb = nullptr; A* pa = pb; pa->hello(); pa->func(); pa->test(); return 0; }
运行结果
A::hello B::func num is 10
问题分析
在 main 函数中,将 pb 指针赋值给 pa 指针,然后通过 pa 指针调用了 hello() 和 func() 函数。
- 由于
hello()函数没有被声明为虚函数,所以调用的是A类中的hello()函数,输出 'A::hello'。 - 而
func()函数被声明为虚函数,在B类中被重写,所以通过pa指针调用的是B类中的func()函数,输出 'B::func'。
此外,在 A 类中定义了一个成员变量 num,并在 test() 函数中输出了它的值,所以调用 pa->test() 时输出 'num is 10'。
结论: 该代码示例展示了 C++ 中虚函数与多态性的应用,通过将基类指针指向派生类对象,可以实现运行时动态绑定,调用派生类中重写的虚函数。
原文地址: https://www.cveoy.top/t/topic/qAkS 著作权归作者所有。请勿转载和采集!