已有类 Time和Date,要求设计一个派生类Birthtime,它是Time和Date的公有派生类,新增一个数据成员childName用于表示小孩的名字,设计主程序显示一个小孩的名字和出生日期时间。数据通过键盘输入,需要判断输入的年月日时分秒是否有效。c++语言
时间: 2023-11-22 14:56:58 浏览: 164
以下是实现Birthtime类的代码:
```cpp
#include <iostream>
using namespace std;
class Time {
protected:
int hour, minute, second;
public:
Time(int hh = 0, int mm = 0, int ss = 0) {
hour = hh;
minute = mm;
second = ss;
}
void setTime(int hh, int mm, int ss) {
hour = hh;
minute = mm;
second = ss;
}
void printTime() {
cout << hour << ":" << minute << ":" << second << endl;
}
};
class Date {
protected:
int year, month, day;
public:
Date(int yy = 0, int mm = 0, int dd = 0) {
year = yy;
month = mm;
day = dd;
}
void setDate(int yy, int mm, int dd) {
year = yy;
month = mm;
day = dd;
}
void printDate() {
cout << year << "-" << month << "-" << day << endl;
}
};
class Birthtime : public Time, public Date {
private:
string childName;
public:
Birthtime(int yy = 0, int mm = 0, int dd = 0, int hh = 0, int mi = 0, int ss = 0, string name = "") : Time(hh, mi, ss), Date(yy, mm, dd) {
childName = name;
}
void setBirthtime(int yy, int mm, int dd, int hh, int mi, int ss, string name) {
Date::setDate(yy, mm, dd);
Time::setTime(hh, mi, ss);
childName = name;
}
void printBirthtime() {
cout << "Child Name: " << childName << endl;
cout << "Birth Date: ";
Date::printDate();
cout << "Birth Time: ";
Time::printTime();
}
};
int main() {
int year, month, day, hour, minute, second;
string name;
cout << "Enter the child's name: ";
getline(cin, name);
cout << "Enter the birth date (yyyy-mm-dd): ";
scanf("%d-%d-%d", &year, &month, &day);
cout << "Enter the birth time (hh:mm:ss): ";
scanf("%d:%d:%d", &hour, &minute, &second);
Birthtime birthtime;
if (year >= 0 && month >= 1 && month <= 12 && day >= 1 && day <= 31 && hour >= 0 && hour <= 23 && minute >= 0 && minute <= 59 && second >= 0 && second <= 59) {
birthtime.setBirthtime(year, month, day, hour, minute, second, name);
birthtime.printBirthtime();
} else {
cout << "Invalid input!" << endl;
}
return 0;
}
```
以上代码实现了一个名为Birthtime的派生类,它继承了Time和Date两个基类,并新增了一个数据成员childName表示小孩的名字。在主程序中,用户输入小孩的名字、出生日期和出生时间,如果输入有效,则将这些数据传递给Birthtime对象并打印出来;否则,提示用户输入无效。
阅读全文