定义一个类vehicle,包含有一个虚函数run()。motor类是vehicle类的派生类,run()用来显示"motor is running”。编写程序并完成测试。 main函数代码如下: int main({ vehicle *v; motor m; v=&m; v->runO;} 运行结果如下: motor is surming
时间: 2024-02-17 22:03:12 浏览: 11
以下是实现代码:
```c++
#include <iostream>
using namespace std;
class vehicle{
public:
virtual void run(){
cout << "Vehicle is running" << endl;
}
};
class motor : public vehicle{
public:
void run(){
cout << "Motor is running" << endl;
}
};
int main(){
vehicle *v;
motor m;
v = &m;
v->run();
return 0;
}
```
输出结果为:
```
Motor is running
```
在 main 函数中,我们先定义了一个 vehicle 类型的指针 v 和一个 motor 类的对象 m。然后将 m 的地址赋值给 v。由于 motor 类继承了 vehicle 类,所以可以将 motor 类的对象指针赋值给 vehicle 类型的指针。
在调用 v->run() 函数时,由于 run() 函数是 vehicle 类的虚函数,所以会根据指针所指向的对象类型来调用对应的函数。在这里,v 指针指向的是 motor 类的对象 m,因此会调用 motor 类中重载的 run() 函数,输出"Motor is running"。
相关问题
有一个交通工具类 vehicle,将它作为基类派生小车类 car,卡车类 truck 和轮船类 boat,定义这些类并定义一个虚函数用来显示各类信息。
好的,根据您的要求,我可以为您介绍一个交通工具类vehicle,并且派生出小车类car、卡车类truck和轮船类boat。以下是各类的定义:
```c++
// 定义交通工具类 vehicle
class Vehicle {
public:
virtual void display() {
cout << "This is a vehicle." << endl;
}
};
// 定义小车类 car
class Car : public Vehicle {
public:
void display() {
cout << "This is a car." << endl;
}
};
// 定义卡车类 truck
class Truck : public Vehicle {
public:
void display() {
cout << "This is a truck." << endl;
}
};
// 定义轮船类 boat
class Boat : public Vehicle {
public:
void display() {
cout << "This is a boat." << endl;
}
};
```
在上面的代码中,我们定义了一个基类Vehicle,并派生出了三个子类:Car、Truck和Boat。其中,Vehicle类中定义了一个虚函数display(),用来显示各个类的信息。在派生类中,我们重写了display()函数,使每个子类都有自己的显示方式。
定义一个交通工具(Vehicle)的类,其中 有数据成员:速度
好的,以下是一个简单的交通工具类的定义,包含了速度这个数据成员:
```python
class Vehicle:
def __init__(self, speed):
self.speed = speed
```
在这个类中,我们定义了一个构造函数 `__init__()`,它接收一个参数 `speed`,并将它赋值给对象的数据成员 `self.speed`。这个类的实例可以表示任何一种交通工具,比如汽车、火车、自行车等等。这个类的实例可以通过 `speed` 属性来访问其速度值。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/msword](https://img-home.csdnimg.cn/images/20210720083327.png)