演示如何隐式的将形参传递给构造函数
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;
}