以及成员函数用于设置和读取属性值,日期类要求支持闰年判断。

以下是代码实现:

#include <iostream>
using namespace std;

class Date {
private:
    int year, month, day;
public:
    Date(int y, int m, int d) {
        year = y;
        month = m;
        day = d;
    }
    int getYear() { return year; }
    int getMonth() { return month; }
    int getDay() { return day; }
    bool isLeapYear() {
        if (year % 4 == 0 && year % 100 != 0 || year % 400 == 0)
            return true;
        else
            return false;
    }
};

class Time {
private:
    int hour, minute, second;
public:
    Time(int h, int m, int s) {
        hour = h;
        minute = m;
        second = s;
    }
    int getHour() { return hour; }
    int getMinute() { return minute; }
    int getSecond() { return second; }
};

class TimeWithDate : public Date, public Time {
public:
    TimeWithDate(int y, int m, int d, int h, int mi, int s) : Date(y, m, d), Time(h, mi, s) {}
};

int main() {
    int year, month, day, hour, minute, second;
    cout << "Enter year, month, day, hour, minute, second: ";
    cin >> year >> month >> day >> hour >> minute >> second;

    TimeWithDate timeWithDate(year, month, day, hour, minute, second);
    cout << "Date: " << timeWithDate.getYear() << "-" << timeWithDate.getMonth() << "-" << timeWithDate.getDay() << endl;
    cout << "Time: " << timeWithDate.getHour() << ":" << timeWithDate.getMinute() << ":" << timeWithDate.getSecond() << endl;
    if (timeWithDate.isLeapYear())
        cout << "This is a leap year." << endl;
    else
        cout << "This is not a leap year." << endl;

    return 0;
}

运行程序,输入日期和时间信息,即可输出设置的日期和时间,以及是否为闰年

C++定义一个日期类Date和一个时间类Time分别用于表示年、月、日和时、分、秒在此基础上再定义一个带日期的时间类TimeWithDate多重继承。并编写主函数测试所定义的类结构实现对时间的设置与读取。 要求:每个类都要写含参的构造函数

原文地址: https://www.cveoy.top/t/topic/fcWk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录