C++级联函数调用

级联函数调用就是类似于下面这种调用函数的方式:

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

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值