实验目的和要求
了解静态联编的动态联编的概念。掌握动态联编的条件。
实验内容
1.分析并调试下列程序。
- #include<iostream>
- using namespace std;
- class Base
- {
- public:
- virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}
- void g(float x){cout<<"Base::g(float)"<<x<<endl;}
- void h(float x){cout<<"Base::h(float)"<<x<<endl;}
- };
- class Derived:public Base
- {
- public:
- virtual void f(float x){cout<<"Derived::f(float}"<<x<<endl;}
- void g(int x){cout<<"Derived::g(int)"<<x<<endl;}
- void h(float x){cout<<"Derived::h(float)"<<x<<endl;}
- };
- int main()
- {
- Derived d;
- Base *pb=&d;
- Derived *pd=&d;
- pb->f(3.14f);
- pd->f(3.14f);
- pb->g(3.14f);
- pb->h(3.14f);
- pd->h(3.14f);
- return 0;
- }
#include<iostream>
using namespace std;
class Base
{
public:
virtual void f(float x){cout<<"Base::f(float)"<<x<<endl;}
void g(float x){cout<<"Base::g(float)"<<x<<endl;}
void h(float x){cout<<"Base::h(float)"<<x<<endl;}
};
class Derived:public Base
{
public:
virtual void f(float x){cout<<"Derived::f(float}"<<x<<endl;}
void g(int x){cout<<"Derived::g(int)"<<x<<endl;}
void h(float x){cout<<"Derived::h(float)"<<x<<endl;}
};
int main()
{
Derived d;
Base *pb=&d;
Derived *pd=&d;
pb->f(3.14f);
pd->f(3.14f);
pb->g(3.14f);
pb->h(3.14f);
pd->h(3.14f);
return 0;
}
(1)找出以上程序中使用了重载和覆盖函数。
(2)写出程序的输出结果,并解释输出结果。
(2)写出程序的输出结果,并解释输出结果。
程序的输出结果如下:

分析:
在程序中pb是基类指针,pd是派生类指针,pd的所有函数调用都只是调用自己的函数
2. 分析并调试下列程序
- #include<iostream>
- using namespace std;
- class Base
- {
- public:
- void f(int x){cout<<"Base::f(int)"<<x<<endl;}
- void f(float x)

本文通过一系列C++代码实例,详细解释了多态性和虚函数的概念,展示了它们在继承和对象调用中的应用。实验内容包括基类与派生类的虚函数覆盖、函数重载、抽象类以及接口实现。最后,文章探讨了重载与覆盖的区别,并解释了静态联编的概念及其优缺点。
最低0.47元/天 解锁文章
5723

被折叠的 条评论
为什么被折叠?



