实验6 多态性与虚函数

本文详细探讨了C++中多态性的概念,通过实例展示了虚函数在实现多态性中的作用。文章分析了函数重载与覆盖的区别,并解释了静态联编与动态联编的工作原理及其在程序中的应用。最后,实验总结强调了理解这些概念对于掌握C++动态联编的重要性。
摘要由CSDN通过智能技术生成


实验目的和要求

     了解静态联编的动态联编的概念。掌握动态联编的条件。
实验内容
1.分析并调试下列程序。
  1. //sy6_1.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. virtual void f(float x){ cout<< "Base::f(float)"<<x<< endl;}
  8. void g(float x){ cout<< "Base::g(float)"<<x<< endl;}
  9. void h(float x){ cout<< "Base::h(float)"<<x<< endl;}
  10. };
  11. class Derived: public Base
  12. {
  13. public:
  14. virtual void f(float x){ cout<< "Derived::f(float}"<<x<< endl;}
  15. void g(int x){ cout<< "Derived::g(int)"<<x<< endl;}
  16. void h(float x){ cout<< "Derived::h(float)"<<x<< endl;}
  17. };
  18. int main()
  19. {
  20. Derived d;
  21. Base *pb=&d;
  22. Derived *pd=&d;
  23. pb->f( 3.14f); //语句1
  24. pd->f( 3.14f); //语句2
  25. pb->g( 3.14f); //语句3
  26. pb->h( 3.14f); //语句4
  27. pd->h( 3.14f); //语句5
  28. return 0;
  29. }

(1)找出以上程序中使用了重载和覆盖函数。

答:Base类中函数void g(); 和void h();与Derived类中的函数void g(); 和void h();函数名相同,参数类型不同,构成了函数重载。

(2)写出程序的输出结果,并解释输出结果。
程序的输出结果如下:
分析:程序首先声明一个基类Base,类中公有成员部分有虚函数f和两个成员函数g、h,接着定义派生类Derived并且继承基类中的公有部分。主函数中先声明一个对象d,接着定义指针pb。然后执行语句1,调用基类中的虚函数,输出第一行结果。接着执行语句2、3、4、5,分别调用派生类中虚函数、基类中的g函数、基类中的h函数,派生类中的h函数,输出第2、3、4、5行结果。
2 . 分析并调试下列程序
  1. //sy6_3.cpp
  2. #include<iostream>
  3. using namespace std;
  4. class Base
  5. {
  6. public:
  7. void f(int x){ cout<<"Base::f(int)"<<x<<endl;}
  8. void f(float x){ cout<<"Base::f(float)"<<x<<endl;}
  9. virtual void g(void){ cout<<"Base::g(void)"<<endl;}
  10. };
  11. class Derived:public Base
  12. {
  13. public:
  14. virtual void g(void){ cout<<"Derived::g(void}"<<endl;}
  15. };
  16. int main()
  17. {
  18. Derived d;
  19. Base *pb=&d;
  20. pb->f(42);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值