C++ 继承实现带日期的时间类 TimeWithDate

本文将使用 C++ 继承机制,利用已有的 TimeDate 类,定义一个包含日期和时间的 TimeWithDate 类。代码示例展示了类的定义和使用方法,并给出了运行结果。

类定义

#include <iostream>
using namespace std;

class Time {
public:
    Time(int h = 0, int m = 0, int s = 0) {
        hour = h;
        minute = m;
        second = s;
    }
    void display() {
        cout << hour << ':' << minute << ':' << second << endl;
    }
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 display() {
        cout << year << '-' << month << '-' << day << endl;
    }
protected:
    int year, month, day;
};

class TimeWithDate : public Time, public Date {
public:
    TimeWithDate(int y = 0, int m = 0, int d = 0, int h = 0, int min = 0, int s = 0) : Time(h, min, s), Date(y, m, d) {}
    void display() {
        cout << year << '-' << month << '-' << day << ' ';
        cout << hour << ':' << minute << ':' << second << endl;
    }
};

int main() {
    int year, month, day, hour, minute, second;
    cin >> year >> month >> day >> hour >> minute >> second;
    TimeWithDate t1(year, month, day, hour, minute, second);
    t1.display();
    return 0;
}

代码说明

  1. 使用 public 继承 TimeDate 类,使得 TimeWithDate 类拥有 TimeDate 类的所有成员变量和方法。
  2. TimeWithDate 类的构造函数中,使用初始化列表分别初始化了 TimeDate 类的成员变量。
  3. 重写了 display 方法,以显示日期和时间。

运行结果

输入示例:

2023 12 25 10 30 45

输出结果:

2023-12-25 10:30:45

总结

通过继承,我们可以方便地扩展现有类,创建新的类,并复用已有类的功能。在本文中,我们利用继承机制,成功地定义了一个包含日期和时间的 TimeWithDate 类。

C++ 继承实现带日期的时间类 TimeWithDate

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

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