2. 已有类Time和Date,要求设计一个派生类Birthtime,它继承了Time和Date,并且增加一个数据成员Childname用于表示小孩的名字,同时设计主程序显示一个小孩的出生时间和名字。C++
时间: 2023-11-27 13:50:58 浏览: 85
下面是一个可能的实现:
```cpp
#include <iostream>
#include <string>
class Date {
public:
Date(int year, int month, int day)
: year_(year), month_(month), day_(day) {}
void show() const {
std::cout << year_ << "-" << month_ << "-" << day_;
}
private:
int year_;
int month_;
int day_;
};
class Time {
public:
Time(int hour, int minute, int second)
: hour_(hour), minute_(minute), second_(second) {}
void show() const {
std::cout << hour_ << ":" << minute_ << ":" << second_;
}
private:
int hour_;
int minute_;
int second_;
};
class Birthtime : public Date, public Time {
public:
Birthtime(int year, int month, int day, int hour, int minute, int second,
const std::string& child_name)
: Date(year, month, day), Time(hour, minute, second),
child_name_(child_name) {}
void show() const {
std::cout << "Child Name: " << child_name_ << std::endl;
std::cout << "Birth Time: ";
Date::show();
std::cout << " ";
Time::show();
std::cout << std::endl;
}
private:
std::string child_name_;
};
int main() {
Birthtime birthtime(2021, 9, 1, 8, 30, 0, "Alice");
birthtime.show();
return 0;
}
```
这个程序中,我们定义了 `Date` 和 `Time` 两个基类,它们分别表示日期和时间。然后我们定义了 `Birthtime` 派生类,它继承了 `Date` 和 `Time` 两个基类,并且增加了一个数据成员 `child_name_` 表示小孩的名字。在 `show()` 函数中,我们先输出小孩的名字,然后调用基类的 `show()` 函数分别输出日期和时间。
在主函数中,我们创建了一个 `Birthtime` 对象,然后调用它的 `show()` 函数显示出生时间和名字。输出结果如下:
```
Child Name: Alice
Birth Time: 2021-9-1 8:30:0
```
相关推荐
![docx](https://img-home.csdnimg.cn/images/20210720083331.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)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)