用c++设计时间类Time和日期类Date,Birthtime类由Time类和Date类派生,并且增加一个数据成员Childname用于表示小孩的姓名,编写程序输出小孩的姓名和出生时间。
时间: 2024-03-22 20:40:23 浏览: 71
下面是时间类Time的实现:
```c++
class Time {
public:
Time(int hour = 0, int minute = 0, int second = 0);
std::string to_string() const;
private:
int hour;
int minute;
int second;
};
Time::Time(int hour, int minute, int second) : hour(hour), minute(minute), second(second) {}
std::string Time::to_string() const {
return std::to_string(hour) + ":" + std::to_string(minute) + ":" + std::to_string(second);
}
```
下面是日期类Date的实现:
```c++
class Date {
public:
Date(int year = 0, int month = 0, int day = 0);
std::string to_string() const;
private:
int year;
int month;
int day;
};
Date::Date(int year, int month, int day) : year(year), month(month), day(day) {}
std::string Date::to_string() const {
return std::to_string(year) + "-" + std::to_string(month) + "-" + std::to_string(day);
}
```
下面是Birthtime类的实现:
```c++
class Birthtime : public Time, public Date {
public:
Birthtime(const std::string& child_name, int year, int month, int day, int hour = 0, int minute = 0, int second = 0);
std::string to_string() const;
private:
std::string child_name;
};
Birthtime::Birthtime(const std::string& child_name, int year, int month, int day, int hour, int minute, int second)
: Time(hour, minute, second), Date(year, month, day), child_name(child_name) {}
std::string Birthtime::to_string() const {
return child_name + " was born on " + Date::to_string() + " at " + Time::to_string();
}
```
现在可以测试一下Birthtime类的功能:
```c++
Birthtime birth_time("Alice", 2021, 8, 1, 10, 30, 0);
std::cout << birth_time.to_string() << std::endl;
```
输出结果为:
```
Alice was born on 2021-8-1 at 10:30:0
```
这个例子展示了如何使用继承来创建新的类,并且如何在子类中调用父类的构造函数。注意,在输出字符串时需要使用 Date::to_string() 和 Time::to_string() 来调用父类的成员函数。
阅读全文