您的当前位置:首页正文

C实验报告-实验5多态性与虚函数

来源:爱站旅游
导读C实验报告-实验5多态性与虚函数
如有你有帮助,请购买下载,谢谢!

实验5 多态性与虚函数

一、实验目的和要求

了解静态联编和动态联编的概念。掌握动态联编的条件。 二、实验内容和原理

事先编写好程序,上机调试和运行程序,分析结果。 (1)实验指导书P96 1~4任选一题。 (2)实验指导书P100 5~6任选一题。 三、实验环境

联想计算机,Windows XP操作系统,Visual C++ 6.0 四、算法描述及实验步骤

(1)编写源程序。

(2)检查程序有无错误(包括语法错误和逻辑错误),有则改之。

(3)编译和连接,仔细分析编译信息,如有错误应找出原因并改正之。

(4)运行程序,分析结果。

(5)将调试好的程序保存在自己的用户目录中,文件名自定。 五、调试过程 1 2

1页

如有你有帮助,请购买下载,谢谢!

六、实验结果 1 5

七、总结

动态联编需要满足3个条件,首先类之间满足类型兼容规则;第二是要声明虚函数;第三是要由成员函数来调用或者是通过基类指针、引用来访问虚函数。 附录:

1. {

public:

virtual void f(float x){cout<<\"Base::f(float)\"<class Derived:public Base

2页

如有你有帮助,请购买下载,谢谢!

{public:

virtual void f(float x){cout<< \"Derived::h(float)\"<int main() {Derived d; Base * pb=&d; Derived *pd=&d; pb->f(3.14f); pb->f(3.14f); pb->g(3.14f); pb->h(3.14f); pb->h(3.14f); return 0; }

2#include using namespace std; #include class Teacher {public:

Teacher(string n,int h); virtual double salary()=0; virtual void print()=0; protected: string name; int lessons; };

Teacher::Teacher(string n,int h) {

name=n; lessons=h; }

class Professor:public Teacher {public:

Professor(string n,int h):Teacher(n,h){}

double salary(){return 5000 + 50 * lessons;} void print(); };

void Professor::print()

{cout<class Associateprofessor:public Teacher {

3页

如有你有帮助,请购买下载,谢谢!

public:

Associateprofessor(string n,int h):Teacher(n,h){} double salary(){return 3000+30*lessons;} void print(); };

void Associateprofessor::print() {

cout< using namespace std; #include class Teacher {public:

Teacher(string n,int h); virtual double salary()=0; virtual void print()=0; protected: string name; int lessons; };

Teacher::Teacher(string n,int h) {

name=n; lessons=h; }

class Professor:public Teacher {public:

Professor(string n,int h):Teacher(n,h){}

double salary(){return 5000 + 50 * lessons;} void print(); };

void Professor::print()

{cout<class Associateprofessor:public Teacher {

public:

Associateprofessor(string n,int h):Teacher(n,h){} double salary(){return 3000+30*lessons;} void print(); };

void Ass me<<\"\Associateprofessor\\"<4页

如有你有帮助,请购买下载,谢谢!

class Lecturer:public Teacher {public:

Lecturer(string n,int h):Teacher(n,h){} double salary(){return 2000+20*lessons;} void print(); };

void Lecturer::print()

{cout<int main()

{Teacher * t[3];

t[0]=new Professor(\"Tang XiHua\

t[1]=new Associateprofessor(\"Li HanPin[2]=new Lecturer(\"Zhang Yue\for(int i=0;i<3;i++) {t[i]->print(); delete t[i]; }

return 0; }

5页

因篇幅问题不能全部显示,请点此查看更多更全内容

Top