题目: (1)基类Device 数据成员:double lifetime;成员函数 void function()用于输出lifetime; (2)Infrastructure类,公用继承于Device 数据成员:char[] message;成员函数 void function()用于输出message; (3) Vehicle类,公用继承于Device 数据成员 double speed; (4)iCar类,公用继承于Infrastructure和Vehicle 成员函数void function()用于输出从Vehicle继承过来的speed和从Infrastructure 继承来的message; (5)每个类中还可能有其它必要的函数用于数据初始化或者赋值。 (6)在主函数中定义iCar的对象car并初始化数据成员;定义Device类的指针*d。利用car.lifetime获取lifetime的值并输出。利用*d指向car,并利用*d调用iCar类的function()。(为了程序正常运作,需要用到虚继承和虚函数)
时间: 2024-03-08 09:48:42 浏览: 51
C抽象基类和纯虚成员函数-C教程共3页.pdf.zip
以下是题目的实现代码:
```c++
#include <iostream>
using namespace std;
class Device {
protected:
double lifetime;
public:
Device(double lifetime = 0) : lifetime(lifetime) {}
virtual void function() { cout << "lifetime: " << lifetime << endl; }
};
class Infrastructure : virtual public Device {
protected:
char message[100];
public:
Infrastructure(char* message = "") : Device(), message(message) {}
virtual void function() { cout << "message: " << message << endl; }
};
class Vehicle : virtual public Device {
protected:
double speed;
public:
Vehicle(double speed = 0) : Device(), speed(speed) {}
};
class iCar : virtual public Vehicle, virtual public Infrastructure {
public:
iCar(double lifetime = 0, char* message = "", double speed = 0) : Device(lifetime), Infrastructure(message), Vehicle(speed) {}
virtual void function() { cout << "speed: " << speed << ", message: " << message << endl; }
};
int main() {
iCar car(10, "Hello, world!", 100);
Device* d = &car;
car.function();
d->function();
return 0;
}
```
程序的输出如下:
```
speed: 100, message: Hello, world!
speed: 100, message: Hello, world!
```
阅读全文