C++练习(类和对象)

C++课程实验题:

1.定义一个time类保存在“htime.h”中,要求:

⑴ 数据成员包含时(hour)、分(minute)、秒(second),为私有成员;

⑵ 能给数据成员提供值的成员函数(默认值为0时0分0秒);

⑶ 能分别取时、分、秒;

⑷ 能输出时、分、秒(用“:”分隔),并显示上午(am)或下午(pm);

⑸ 有默认值的构造函数(默认值为0时0分0秒)。

说明:成员函数均定义为公有成员。

2.编写一个测试time类的main()函数(存放在exp_104.cpp)中。要求:

⑴ 定义对象、对象指针、对象的引用;

⑵ 用输入的值设置时间;

⑶ 用输出时、分、秒的成员函数显示时间;

⑷ 用取时、分、秒的成员函数以“  时  分  秒”的格式显示时间;

⑸ 分别用对象、对象指针、对象的引用调用成员函数。

编译环境:VS2022

头文件(htime.h):

using namespace std;
class Time {
private:
    int hour;
    int minute;
    int second;
public:
    Time(int h = 0, int m = 0, int s = 0);  //设置默认参数0,0,0

    void setTime(int h, int m, int s);   //设置时间
    int getHour()  {                   //读取小时 
        return hour;
    }

    int getMinute() {                  //读取分钟
        return minute;
    }
     
    int getSecond()  {                 //读取秒
        return second;
    }
    void display() ;                  //转换十二小时制
};

Time::Time(int h, int m, int s) {
    setTime(h, m, s);
}
void Time::setTime(int h, int m, int s)
{
    cin >> h >> m >> s;
    hour = (h >= 0 && h < 24) ? h : 0;
    minute = (m >= 0 && m < 60) ? m : 0;
    second = (s >= 0 && s < 60) ? s : 0;
}
void Time::display()  {
    cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ':'
        << (minute < 10 ? "0" : "") << minute << ':'
        << (second < 10 ? "0" : "") << second
        << (hour < 12 ? " am" : " pm") << endl;
}

源文件(主函数):

#include<iostream>
#include"htime.h"
using namespace std;
int main()
{
    int h, m, s;
    Time t1, t2;
    Time* p;
    p = &t2;
    Time& t3 = t1;
    cin >> h >> m >> s;
    t1.setTime(h,m,s);
    cin >> h >> m >> s;
    t2.setTime(h,m,s);
    t1.display();
    p->display();
    cout << "t1.hour:" << t3.getHour() << endl;
    cout << "t1.minute:" << t3.getMinute() << endl;
    cout << "t1.second:" << t3.getSecond() << endl;
    cout << "t2.hour:" << t2.getHour() << endl;
    cout << "t2.minute:" << t2.getMinute() << endl;
    cout << "t2.second:" << t2.getSecond() << endl;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CSVN.

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值