已有类Time和Date,要求设计一个 派生类Birthtime,它继承类Time和Date,并且增加一个数据成员Child name用于表示小孩的名字,同时设计主程序显示一个小孩的出生时间和名字。
时间: 2024-05-10 08:19:37 浏览: 92
以下是实现该要求的代码:
```cpp
#include <iostream>
#include <string>
using namespace std;
class Time {
public:
Time(int h = 0, int m = 0, int s = 0) {
hour = h;
minute = m;
second = s;
}
void displayTime() const {
cout << hour << ":" << minute << ":" << second;
}
protected:
int hour, minute, second;
};
class Date {
public:
Date(int y = 0, int m = 0, int d = 0) {
year = y;
month = m;
day = d;
}
void displayDate() const {
cout << year << "-" << month << "-" << day;
}
protected:
int year, month, day;
};
class Birthtime : public Time, public Date {
public:
Birthtime(int y = 0, int m = 0, int d = 0, int h = 0, int min = 0, int s = 0, const string& name = "") : Time(h, min, s), Date(y, m, d), childName(name) {}
void display() const {
cout << "Child's name: " << childName << endl;
cout << "Birth date: ";
displayDate();
cout << endl;
cout << "Birth time: ";
displayTime();
cout << endl;
}
private:
string childName;
};
int main() {
Birthtime b(2022, 9, 18, 8, 30, 0, "Alice");
b.display();
return 0;
}
```
运行结果如下:
```
Child's name: Alice
Birth date: 2022-9-18
Birth time: 8:30:0
```
阅读全文