级联函数调用就是类似于下面这种调用函数的方式:
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);

最低0.47元/天 解锁文章
229

被折叠的 条评论
为什么被折叠?



