1、掌握继承机制。
2、掌握虚函数。
3、理解并掌握虚基类。
二、实验内容
1、编写一个程序:设计一个汽车类,数据成员有*个数、车重。小车类是汽车类的私有派生类,包含载客量。卡车类是汽车类的私有派生类,包含载客数和载重量。每个类都有数据的输出方法。
#include<iostream> using namespace std; //汽车类 class car { public: int wheel;//*个数 float weight;//车重 car(int a=0,float b=0); void carprint();//汽车类的输出函数 }; //小车类 class dolly:private car { private: int busload;//载客量 public: dolly(int c=24):car(4,2) { busload=c; } void dollyprint();//小车类的输出函数 }; //卡车类 class truck:private car { private: int busload;//载客量 float upweight;//载重量 public: truck(int c=24,float d=30):car(4,2) { busload=c; upweight=30; } void truckprint();//卡车类的输出函数 }; int main() { car c1(4,2); c1.carprint(); dolly c2(24); c2.dollyprint(); truck c3(24,3); c3.truckprint(); return 0; } //汽车类的构造函数 car::car(int a,float b) { wheel=a; weight=b; } //汽车类的输出函数 void car::carprint() { cout<<"汽车类:"<<endl; cout<<"*个数为:"<<wheel<<"个"<<endl; cout<<"车重为:"<<weight<<"吨"<<endl; cout<<endl<<endl; } //小车类的输出函数 void dolly::dollyprint() { cout<<"小车类:"<<endl; cout<<"*个数为:"<<wheel<<"个"<<endl; cout<<"车重为:"<<weight<<"吨"<<endl; cout<<"载客量为:"<<busload<<"位"<<endl; cout<<endl<<endl; } //卡车类的输出函数 void truck::truckprint() { cout<<"卡车类:"<<endl; cout<<"*个数为:"<<wheel<<"个"<<endl; cout<<"车重为:"<<weight<<"吨"<<endl; cout<<"载客量为:"<<busload<<"位"<<endl; cout<<"载重量为:"<<busload<<"吨"<<endl; }
2、虚基类为Shape,从Shape派生出矩形类(左上角点、宽、高)、椭圆类(横轴、纵轴)。给出各个类的构造函数,成员初始化,在基类中定义虚函数GetArea()(计算面积),在派生类中改写。写出该程序的实现。
#include<iostream> #define PI 3.14 using namespace std; //形状类 class Shape { public: int x,y; int wide,high; Shape(){}; virtual void GetArea()=0;//虚函数GetArea()(计算面积) virtual ~Shape(){}; }; //矩形类 class rectangle:public Shape { private: int x,y; int wide,high; public: rectangle(int a,int b,int c,int d);//矩形类的构造函数 void GetArea(); }; //椭圆类 class ellipse:public Shape { private: int x,y; int wide,high; public: ellipse(int a,int b,int c,int d);//椭圆类的构造函数 void GetArea(); }; int main() { rectangle ob1(3,4,6,8); ob1.GetArea(); ellipse ob2(0,0,2,2); ob2.GetArea(); return 0; } //矩形类的构造函数 rectangle::rectangle(int a,int b,int c,int d) { x=a; y=b; wide=c; high=d; } //椭圆类的构造函数 ellipse::ellipse(int a,int b,int c,int d) { x=a; y=b; wide=c; high=d; } void rectangle::GetArea() { cout<<"矩形类"<<endl; cout<<"左上角点的坐标为:"<<'('<<x<<','<<y<<')'<<endl; cout<<"矩形的宽为:"<<wide<<endl; cout<<"矩形的高为:"<<high<<endl; cout<<"矩形的面积为:"<<wide*high<<endl<<endl; } void ellipse::GetArea() { float area; area=PI*wide*high/4; cout<<"椭圆类"<<endl; cout<<"椭圆的横轴为:"<<wide<<endl; cout<<"椭圆的长轴为:"<<high<<endl; cout<<"椭圆的面积为:"<<area<<endl; }