Time 类的案例学习--具有默认实参的构造函数

演示如何隐式的将形参传递给构造函数

Time.h

#ifndef TIME_H
#define TIME_H
class Time{
public:
    Time(int=0, int=0, int=0);
    void setTime(int, int, int);
    void setHour(int);
    void setMinute(int);
    void setSecond(int);

    int getHour();
    int getMinute();
    int getSecond();

    void printUniversal();
    void printStandard();
private:
    int hour;
    int minute;
    int second;
};
#endif

Time.cpp

#include<iostream>
#include<iomanip>
#include"Time.h"
using namespace std;

Time::Time(int hr,int min,int sec){
    setTime(hr, min, sec);
}
void Time::setTime(int h, int m, int s){
    setHour(h);
    setMinute(m);
    setSecond(s);
}
void Time::setHour(int h){
    hour = (h >= 0 && h < 24) ? h : 0;
}
void Time::setMinute(int m){
    minute = (m >= 0 && m <= 60) ? m : 0;
}
void Time::setSecond(int s){
    second = (s >= 0 && s <= 60) ? s : 0;
}
int Time::getHour(){
    return hour;
}
int Time::getMinute(){
    return minute;
}
int Time::getSecond(){
    return second;
}
void Time::printUniversal(){
    cout << setfill('0') << setw(2) << getHour()<<":"<<setw(2)<<getMinute()<<":"<<setw(2)<< getSecond();
}

测试.cpp

#include<iostream>
#include"Time.h"
using namespace std;
int main(){
    Time t1;//all arguments defaulted省略所有实参
    Time t2(2);
    Time t3(21,34);
    Time t4(12, 25, 42);
    Time t5(27, 74, 99);
    cout << "Constructed with:\n\nt1:all arguments defaulted\n";
    t1.printUniversal();
    cout << "\n";
    t1.printStandard();

    cout << "\n\nt2:hour specified:minute and second defaulted\n";
    t2.printUniversal();
    cout << "\n";
    t2.printStandard();

    cout << "\n\nt3:hour and minute specified:second defaulted\n";
    t3.printUniversal();
    cout << "\n";
    t3.printStandard();

    cout << "\n\nt4:hour and minute and second all specified\n";
    t4.printUniversal();
    cout << "\n";
    t4.printStandard();

    cout << "\n\nt5:all are invalid elements\n";
    t5.printUniversal();
    cout << "\n";
    t5.printStandard();
    cout << endl;
 

    cout << endl;

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

小菜鸡变形记

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

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

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

打赏作者

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

抵扣说明:

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

余额充值