一、实验目的
- 理解继承的概念;
- 掌握虚函数的定义;
- 掌握虚函数实现多态的方法;
二、实验内容和要求
定义汽车类Auto(属性:轮子数wheel,颜色color,行为:前进move),由其派生出卡车类Truck(属性:装载量load,行为:开车门open),二者都包含虚函数speak()、构造函数和析构函数,声明一个Auto指针,分别指向Auto对象和Truck对象,调用speak()函数,观察运行结果。
三、实验代码
#include<iostream>
using namespace std;
class Auto
{
private:
int wheel;
const char *color;
public:
Auto(int wheel,const char *color)
{
this->wheel=wheel;
this->color=color;
}
~Auto()
{
cout<<"析构函数:"<<wheel<<'\n';
}
void move()
{
cout<<"汽车前进\n"<<'\n';
}
virtual void speak()
{
cout << "汽车类虚函数" << '\n';
cout << "轮子数:" << wheel << '\n';
cout << "颜色:" << color << '\n';
}
};
class Truck:public Auto
{
private:
double load; //装载量,单位t吨
public:
Truck(int wheel,const char *color,double load):Auto(wheel,color)
{
this->load=load;
}
~Truck()
{
cout<<"析构函数:"<<"Truck"<<'\n';
}
void open()
{
cout<<"汽车门打开\n"<<'\n';
}
void speak()
{
cout << "卡车类虚函数" << '\n';
Auto::speak();
cout<<"装载量:"<<load<<'\n';
}
};
int main()
{
Auto a1(4,"Black");
Truck t1(6,"Blue",10);
Auto *obj=&a1;
obj->speak();
a1.move();
obj=&t1;
obj->speak();
t1.open();
system ("pause");
return 0;
}