题目: 设计基类Device,数据成员:double lifetime;成员函数 void function()用于输出lifetime; Infrastructure类,公用继承于Device,数据成员:char[] message;成员函数 void function()用于输出message; Vehicle类,公用继承于Device 数据成员 double speed; iCar类,公用继承于Infrastructure和Vehicle 成员函数void function()用于输出从Vehicle继承过来的speed和从Infrastructure 继承来的message; 每个类中还可能有其它必要的函数用于数据初始化或者赋值。 在主函数中定义iCar的对象car并初始化数据成员;定义Device类的指针*d。利用car.lifetime获取lifetime的值并输出。利用*d指向car,并利用*d调用iCar类的function()。(为了程序正常运作,需要用到虚继承和虚函数)
时间: 2024-03-08 18:49:37 浏览: 15
好的,我来解答你的问题。
这是一个关于C++类的问题,需要设计一个基类 `Device`,以及三个派生类 `Infrastructure`、`Vehicle` 和 `iCar`。其中 `iCar` 类同时继承了 `Infrastructure` 和 `Vehicle` 类,需要实现一个函数用于输出从 `Vehicle` 继承过来的 `speed` 和从 `Infrastructure` 继承来的 `message`。
下面是具体的代码实现:
```cpp
#include<iostream>
using namespace std;
class Device{
public:
double lifetime;
virtual void function(){
cout<<"lifetime: "<<lifetime<<endl;
}
};
class Infrastructure:virtual public Device{
public:
char message[100];
virtual void function(){
cout<<"message: "<<message<<endl;
}
};
class Vehicle:virtual public Device{
public:
double speed;
};
class iCar:public Infrastructure, public Vehicle{
public:
void function(){
cout<<"speed: "<<speed<<endl;
Infrastructure::function();
}
};
int main(){
iCar car;
car.lifetime = 10.5;
car.speed = 120;
strcpy(car.message, "Hello, world!");
Device *d = &car;
cout<<"lifetime from car: "<<car.lifetime<<endl;
d->function();
return 0;
}
```
在这段代码中,我们首先定义了一个基类 `Device`,其中包含了一个数据成员 `lifetime` 和一个虚函数 `function()`,用于输出 `lifetime`。接着,我们定义了一个派生类 `Infrastructure`,其中包含了一个数据成员 `message` 和一个虚函数 `function()`,用于输出 `message`。
类 `Vehicle` 继承自基类 `Device`,其中包含了一个数据成员 `speed`。类 `iCar` 同时继承自 `Infrastructure` 和 `Vehicle`,重载了虚函数 `function()`,用于输出 `speed` 和 `message`。
在主函数中,我们定义了一个 `iCar` 类的对象 `car`,并初始化了它的数据成员。接着,我们定义了一个 `Device` 类的指针 `d`,并将它指向 `car`。通过 `car.lifetime` 获取 `lifetime` 的值并输出。利用 `d` 调用 `iCar` 类的 `function()`,因为 `function()` 是虚函数,所以会调用 `iCar` 类中的 `function()`。输出结果为:
```
lifetime from car: 10.5
speed: 120
message: Hello, world!
```
希望我的回答能够帮助到你!