级联函数调用就是类似于下面这种调用函数的方式:
t.setHour(18).setMinute(30).setSecond(22);
它可以把原来需要三行的语句压缩到一行,而且很具有可读性
要实现这样的调用,就必须在类的成员函数之中,返回一个*this指针,这也是实现级联函数调用的关键。
所以,代码实现就像下面这样子:
Time.h
#pragma once
class Time
{
public:
explicit Time(int h = 0, int m = 0, int s = 0);
//set functions(the Time& return types enable cascading)
Time& setTime(int h, int m, int s);
Time& setHour(int h);
Time& setMinute(int m);
Time& setSecond(int s);
//get functions
unsigned int getHour()const;
unsigned int getMinute() const;
unsigned int getSecond() const;
void printUniversal() const;
void printStandard() const;
private:
unsigned int hour, minute, second;
};
Time.cpp
#include "Time.h"
#include<iostream>
#include<stdexcept>
#include<iomanip>
using namespace std;
Time::Time(int h, int m, int s)
{
setTime(h, m, s);
}
Time& Time::setTime(int h, int m, int s)
{
setHour(h);
setMinute(m);
setSecond(s);
return *this;
}
Time& Time::setHour(int h)
{
if (h >= 0 && h < 24)
hour = h;
else throw invalid_argument("hour must be 0-23");
return *this;//enable cascading
}
Time& Time::setMinute(int m)
{
if (m >= 0 && m < 60)
minute = m;
else throw invalid_argument("minute must be 0-59");
return *this;//enable cascading
}
Time& Time::setSecond(int s)
{
if (s >= 0 && s < 60)
second = s;
else throw invalid_argument("second must be 0-59");
return *this;//enable cascading
}
unsigned int Time::getHour() const
{
return this->hour;
}
unsigned int Time::getMinute() const
{
return this->minute;
}
unsigned int Time::getSecond() const
{
return this->second;
}
//print universal-time format (HH:MM:SS)
void Time::printUniversal() const
{
cout << setfill('0') << setw(2) << this->hour << ":" << setw(2) << this->minute << ":" << setw(2) << this->second;
}
//print standard-time format (HH:MM:SS AM or PM)
void Time::printStandard() const
{
cout << ((hour == 0 || hour == 12) ? 12 : hour % 12) << ":" << setfill('0') << setw(2) << minute << ":"
<< setw(2) << second << setw(2) << ((hour < 12) ? " AM" : " PM");
}
main.cpp
#include<iostream>
#include"Time.h"
using namespace std;
int main()
{
Time t;
//级联函数调用
t.setHour(18).setMinute(30).setSecond(22);
cout << "Universal time: ";
t.printUniversal();
cout << "\nStandard time: ";
t.printStandard();
cout << "\n\nNew standard time: ";
t.setTime(20, 20, 20).printStandard();
}
最终程序输出结果:
Universal time: 18:30:22
Standard time: 6:30:22 PM
New standard time: 8:20:20 PM
转载请注明来源:https://www.longjin666.top/?p=831
欢迎关注我的公众号“灯珑”,让我们一起了解更多的事物~