下图所示为各个类的继承关系,分别定义交通工具类Vehicle、汽车类Automobile、船类Bo
下图所示为各个类的继承关系,分别定义交通工具类Vehicle、汽车类Automobile、船类Boat和轮船类Ship,其中Vehicle类为抽象类,定义虚函数displ...
下图所示为各个类的继承关系,分别定义交通工具类Vehicle、汽车类Automobile、船类Boat 和轮船类Ship,其中Vehicle类为抽象类,定义虚函数display用来显示各类的相关信息(This is a…),编写主函数对其加以测试(要求体现多态性)。
展开
展开全部
#include <stdio.h>
#include <iostream>
using namespace std;
class Vehicle
{
public:
virtual ~Vehicle()
{
}
virtual void display() = 0;
};
class Automobile : public Vehicle
{
public:
virtual ~Automobile()
{
}
virtual void display()
{
cout << "This is a automobile" << endl;
}
};
class Boat : public Vehicle
{
public:
virtual ~Boat()
{
}
virtual void display()
{
cout << "This is a boat" << endl;
}
};
class Ship : public Boat
{
public:
virtual ~Ship()
{
}
virtual void display()
{
cout << "This is a ship" << endl;
}
};
int main()
{
Vehicle *p1 = new Automobile();
Vehicle *p2 = new Boat();
Vehicle *p3 = new Ship();
p1->display();
p2->display();
p3->display();
delete p1;
delete p2;
delete p3;
return 0;
}
Linux 环境编译及测试结果如下:
[root@iZ25a38chb4Z test]# g++ -o test -g3 -Wall test.cpp
[root@iZ25a38chb4Z test]# ./test
This is a automobile
This is a boat
This is a ship
main 函数中,创建了 3 个子类对象,均用抽象类指针保存,通过抽象类指针调用虚函数。
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询