#include using namespace std; class A { public: void hello() { cout << 'A::hello' << endl; } virtual void func() { cout << ' A::func' << endl; } void test() { cout << ' num is' << num << endl; } int num = 10;

}; 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++ 中虚函数与多态性的应用,通过将基类指针指向派生类对象,可以实现运行时动态绑定,调用派生类中重写的虚函数。

C++ 虚函数与多态性示例:详解运行结果及问题分析

原文地址: https://www.cveoy.top/t/topic/qAkS 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录