C++实例---输出时间(类的练习)

运行环境:macOS shell

代码:

#include <iostream>
#include <iomanip>
#include <string>
using namespace std;

typedef     char        string80[80];
class Date
{

public:
    Date() {}
    Date(int y, int m, int d)
    {
        SetDate(y,m,d);
    }
    void SetDate(int y, int m, int d)
    {
        Year = y;
        Month = m;
        Day = d;
    }
    string80 &GetStringDate(string80 &Date)
    {
        sprintf(Date, "%d/%d/%d", Year ,Month, Day);
        return Date;
    }
    protected:
        int Year, Month, Day;

};

class Time
{
public:
    Time() {}
    Time(int h, int m, int s)
    {
        SetTime(h,m,s);
    }
    void SetTime(int h, int m, int s)
    {
        Hours = h;
        Minutes = m;
        Second = s;
    }
    string80 &GetStringTime(string80 &Time)
    {
        sprintf(Time, "%d:%d:%d", Hours ,Minutes, Second);
        return Time;
    }
    protected:
        int Hours, Minutes, Second;
};

class TimeDate:public Date, public Time
{
public:
    TimeDate():Date() {}
    TimeDate(int y, int mo, int d, int h, int mi, int s):Date(y,mo,d),Time(h,mi,s)
    {}
    string80 & GetStringDT(string80 &DTstr)
    {
        sprintf(DTstr, "%d/%d/%d;%d:%d:%d",Year,Month,Day,Hours,Minutes,Second);
        return DTstr;
    }
};

int main ()
{
    TimeDate dat1, dat2(2017,2,17,17,25,33);
    string80 DemoStr;
    dat1.SetDate(2017,1,17);
    dat1.SetTime(17,25,33);
    cout<<"The dat1 date is : "<<dat1.GetStringDate(DemoStr)<<endl;
    cout<<"The dat1 time is : "<<dat1.GetStringTime(DemoStr)<<endl;
    cout<<"The dat1 date and time is : "<<dat1.GetStringDT(DemoStr)<<endl;
    cout<<"the dat2 date and time is : "<<dat2.GetStringDT(DemoStr)<<endl;
    return 0;
}

运行结果:
这里写图片描述

猜你喜欢

转载自blog.csdn.net/huazhen1234/article/details/55517971