当前位置:文档之家› C实验报告-实验5多态性与虚函数

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

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
实验5多态性与虚函数
一、实验目的和要求
了解静态联编和动态联编的概念。掌握动态联编的条件。
二、实验内容和原理
事先编写好程序,上机调试和运行程序,分析结果。
(1)实验指导书P96 1~4任选一题。
(2)实验指导书P100 5~6任选一题。
三、实验环境
联想计算机,Windows XP操作系统,Visual C++ 6.0
四、算法描述及实验步骤
(1)编写源程序。
(2)检查程序有无错误(包括语法错误和逻辑错误),有则改之。
(3)编译和连接,仔细分析编译信息,如有错误应找出原因并改正之。
(4)运行程序,分析结果。
(5)将调试好的程序保存在自己的用户目录中,文件名自定。
五、调试过程
1
2
六、实验结果
1
5
七、总结
动态联编需要满足3个条件,首先类之间满足类型兼容规则;第二是要声明虚函数;第三是要由成员函数来调用或者是通过基类指针、引用来访问虚函数。
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<<name<<"\tProfessor\t\t"<<lessons<<"lessonseacher * t[3];
t[0]=new Professor("Tang XiHua",12);
t[1]=new Associateprofessor("Li HanPin",16);
};
class Derived:public Base
{public:
virtual void f(float x){cout<<
"Derived::h(float)"<<x<<endl;}
};
int main()
{Derived d;
Base * pb=&d;
Derived *pd=&d;
pb->f(3.14f);
cout<<"\tearned¥"<<salary()<<endl;
}
class Associateprofessor:public Teacher
{
public:
Associateprofessor(string n,int h):Teacher(n,h){}
double salary(){return 3000+30*lessons;}
pb->f(3.14f);
pb->g(3.14f);
pb->h(3.14f);
pb->h(3.14f);
return 0;
}
2#include<iostream>
using namespace std;
#include<string>
class Teacher
{public:
Teacher(string n,int h);
void print();
};
void Ass me<<"\tAssociateprofessor\t"<<lessons<<"lessons";
cout<<"\tearned¥"<<salary()<<endl;
}
class Lecturer:public Teacher
{public:
Lecturer(string n,int h):Teacher(n,h){}
void print();
};
void Associateprofessor::print()
{
cout<<na#include<iostream>
using namespace std;
#include<string>
class Teacher
{public:
Teacher(string n,int h);
{public:
Professor(string n,int h):Teacher(n,h){}
double salary(){return 5000 + 50 * lessons;}
void print();
};
void Professor::print()
{cout<<name<<"\tProfessor\t\t"<<lessons<<"lessons";
double salary(){return 2000+20*lessons;}
void print();
};
void Lecturer::print()
{cout<<name<<"\tLecturer\t\t"<<lessons<<"lessons";
cout<<"\tearned¥"<<salary()<<endl;
附录:
1.
{
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;}
cout<<"\tearned¥"<<salary()<<endl;
}
class Associateprofessor:public Teacher
{
public:
Associateprofessor(string n,int h):Teacher(n,h){}
double salary(){return 3000+30*lessons;}
相关主题