Time

作者: 修夏之夏i | 来源:发表于2018-05-27 00:42 被阅读24次

1.定义一个time类保存在“htime.h”中,要求:
⑴ 数据成员包含时(hour)、分(minute)、秒(second)为私有成员;
⑵ 能给数据成员提供值的成员函数(默认值为0时0分0秒);
⑶ 能分别取时、分、秒;
⑷ 能输出时、分、秒(用“:”分隔),并显示上午(am)或下午(pm);
⑸ 有默认值的构造函数(默认值为0时0分0秒)。
说明:成员函数均定义为公有成员。
2.编写一个测试time类的main()函数(存放在exp_104.cpp)中。要求:
⑴ 定义对象、对象指针、对象的引用;
⑵ 用输入的值设置时间;
⑶ 用输出时、分、秒的成员函数显示时间;
⑷ 用取时、分、秒的成员函数以“ 时 分 秒”的格式显示时间;
⑸ 分别用对象、对象指针、对象的引用调用成员函数。

htime.h

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

//关于时分秒的头文件

class Time
{
private:
    int hour;
    int minute;
    int second;

public:
    Time() //无参构造函数 对成员初始化
    {
        hour = 0;
        minute = 0;
        second = 0;
    }
    ~Time(){}
    void set_time()
    {
        cin >> hour;
        cin >> minute;
        cin >> second;
    }
    int get_hour()
    {
        if (hour >= 0 && hour <= 24)
            return hour;
        else
        {
            cout << "非法时间" << endl<<endl;
            return 0;
        }
    }
    int get_minute()
    {
        if (minute >= 0 && minute <= 59)
            return minute;
        else
        {
            cout << "非法时间" << endl<<endl;
            return 0;
        }
    }
    int get_second()
    {
        if (second >= 0 && second<=59)
            return second;
        else
        {
            cout << "非法时间" << endl<<endl;
            return 0;
        }
    }
    
    void print()
    {
        cout << hour << ":" << minute << ":" << second;
        if (hour > 0 && hour <12)
        {
            cout << "am "<<endl;
        }
        else
            cout << "pm "<<endl;
    }
};

test.cpp

#define _CRT_SECURE_NO_WARNINGS 1
#include<iostream>
using namespace std;

#include"htime.h"
#include <math.h>

int main()
{
    Time T; //定义对象
    Time *p; //定义对象指针
    Time &S(T);//定义对象的引用 起别名 不开辟空间 不调用构造函数
    p = &T;

    cout << "定义对象----------------" << endl;  
    T.set_time();
    if (T.get_hour() && T.get_minute() && T.get_second())
    {
        T.print();
        cout << T.get_hour() << "时" << T.get_minute() << "分" << T.get_second() << "秒" << endl << endl;
    }
        
    
    cout << "对象指针----------------" << endl;
    p->set_time();
    if (p->get_hour() && p->get_minute() && p->get_second())
    {
        p->print();
        cout << p->get_hour() << "时" << p->get_minute() << "分" << p->get_second() << "秒" << endl << endl;
    }

    cout << "对象引用----------------" << endl;
    S.set_time();
    if (S.get_hour() && S.get_minute() && S.get_second())
    {
        S.print();
        cout << S.get_hour() << "时" << S.get_minute() << "分" << S.get_second() << "秒" << endl << endl;
    }
    return 0;
}
运行结果: time.png

相关文章

网友评论

    本文标题:Time

    本文链接:https://www.haomeiwen.com/subject/ofivjftx.html