第六章:多态性与虚函数

本文通过实例代码探讨了C++中的多态性和虚函数,包括基类和派生类的成员函数重写,以及动态绑定和静态联编的区别。通过实验展示了如何利用虚函数实现对象的动态类型识别和方法调用。
摘要由CSDN通过智能技术生成

一:实验目的和要求

了解静态联编的动态联编的概念。掌握动态联编的条件。
实验内容
1.分析并调试下列程序。

[html]  view plain   copy
  1. #include<iostream>   
  2. using namespace std;   
  3. class Base   
  4. {   
  5.     public:   
  6.         virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}   
  7.         void g(float x){cout<<"Base::g(float)"<<x<<endl;}   
  8.         void h(float x){cout<<"Base::h(float)"<<x<<endl;}   
  9. };   
  10. class Derived:public Base   
  11. {   
  12.    public:   
  13.         virtual void f(float x){cout<<"Derived::f(float}"<<x<<endl;}   
  14.         void g(int x){cout<<"Derived::g(int)"<<x<<endl;}   
  15.         void h(float x){cout<<"Derived::h(float)"<<x<<endl;}   
  16. };   
  17. int main()   
  18. {   
  19.     Derived d;   
  20.     Base *pb=&d;   
  21.     Derived *pd=&d;   
  22.     pb->f(3.14f);   
  23.     pd->f(3.14f);   
  24.     pb->g(3.14f);   
  25.     pb->h(3.14f);   
  26.     pd->h(3.14f);   
  27.     return 0;   
  28. }   
[html]  view plain   copy
  1. #include<iostream>    
  2. using namespace std;    
  3. class Base    
  4. {    
  5.     public:    
  6.         virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}    
  7.         void g(float x){cout<<"Base::g(float)"<<x<<endl;}    
  8.         void h(float x){cout<<"Base::h(float)"<<x<<endl;}    
  9. };    
  10. class Derived:public Base    
  11. {    
  12.    public:    
  13.         virtual void f(float x){cout<<"Derived::f(float}"<<x<<endl;}    
  14.         void g(int x){cout<<"Derived::g(int)"<<x<<endl;}    
  15.         void h(float x){cout<<"Derived::h(float)"<<x<<endl;}    
  16. };    
  17. int main()    
  18. {    
  19.     Derived d;    
  20.     Base *pb=&d;    
  21.     Derived *pd=&d;    
  22.     pb->f(3.14f);    
  23.     pd->f(3.14f);    
  24.     pb->g(3.14f);    
  25.     pb->h(3.14f);    
  26.     pd->h(3.14f);    
  27.     return 0;    
  28. }    
(1)找出以上程序中使用了重载和覆盖函数。
(2)写出程序的输出结果,并解释输出结果
程序的输出结果如下:

分析:
在程序中pb是基类指针,pd是派生类指针,pd的所有函数调用都只是调用自己的函数

2. 分析并调试下列程序

[html]  view plain   copy
  1. #include<iostream>     
  2. using namespace std;     
  3. class Base     
  4. {     
  5.     public:     
  6.         void f(int x){cout<<"Base::f(int)"<<x<<endl;}     
  7.         void f(float x){cout<<"Base::f(float)"<<x<<endl;}     
  8.        virtual void g(void){cout<<"Base::g(void)"<<endl;}     
  9. };     
  10. class Derived:public Base     
  11. {     
  12.     public:     
  13.         virtual void g(void){cout<<"Derived::g(void}"<<endl;}     
  14. };     
  15. int main()     
  16. {     
  17.     Derived d;     
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值