下图所示为各个类的继承关系,分别定义交通工具类Vehicle、汽车类Automobile、船类Bo

2024-12-30 08:18:57
推荐回答(1个)
回答1:

#include 
#include 
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 个子类对象,均用抽象类指针保存,通过抽象类指针调用虚函数。