c++ .有一个交通工具类vehicle,将它作为基类派生小车类car、卡车类truck 和轮船类boat, 定义这些类并定义一个虚函数用来显示各类信息。代码
时间: 2024-04-29 11:22:25 浏览: 130
C++源代码汽车类
以下是相关的C++代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Vehicle {
public:
virtual void display() {
cout << "This is a vehicle." << endl;
}
};
class Car : public Vehicle {
public:
void display() override {
cout << "This is a car." << endl;
}
};
class Truck : public Vehicle {
public:
void display() override {
cout << "This is a truck." << endl;
}
};
class Boat : public Vehicle {
public:
void display() override {
cout << "This is a boat." << endl;
}
};
int main() {
Vehicle* v1 = new Car();
Vehicle* v2 = new Truck();
Vehicle* v3 = new Boat();
v1->display();
v2->display();
v3->display();
delete v1;
delete v2;
delete v3;
return 0;
}
```
在这个示例代码中,我们定义了一个名为Vehicle的基类,并定义了一个名为display()的虚函数。然后,我们创建了三个派生类:Car、Truck和Boat,它们都继承了Vehicle类,并重写了display()函数。最后,我们在main函数中创建了一个指向每个类的指针,并调用了它们的display()函数来显示各自的信息。当然,在程序结束前,我们也需要释放分配给指针的内存。
阅读全文