c++实现有一个交通工具类vehicle,将它作为基类派生小车类car,卡车类trunk和轮船类船,定义这些类并定义一个虚函数用来显示各类的信息。- 小车输出型号 - 卡车输出耗油量 - 轮船输出吨位 输入格式 标记(1->小车,2->卡车,3->轮船) 输出格式 输出信息
时间: 2024-05-10 17:16:01 浏览: 161
以下是 C++ 实现:
```cpp
#include <iostream>
using namespace std;
class Vehicle {
public:
virtual void showInfo() {
cout << "This is a vehicle." << endl;
}
};
class Car : public Vehicle {
public:
void showInfo() {
cout << "This is a car. Model: xxx." << endl;
}
};
class Trunk : public Vehicle {
public:
void showInfo() {
cout << "This is a trunk. Fuel consumption: xxx." << endl;
}
};
class Ship : public Vehicle {
public:
void showInfo() {
cout << "This is a ship. Tonnage: xxx." << endl;
}
};
int main() {
int type;
cin >> type;
Vehicle *v;
switch (type) {
case 1:
v = new Car();
break;
case 2:
v = new Trunk();
break;
case 3:
v = new Ship();
break;
default:
cout << "Invalid type." << endl;
return 0;
}
v->showInfo();
delete v;
return 0;
}
```
输入一个标记,根据标记创建相应的对象,并调用虚函数 `showInfo()` 显示信息。
阅读全文