C++运算符重载——重载限制 及 重载输出类对象

使用运算符时,不能违反原来的语法规则,不能修改优先级
sizeof,.*,?:,:: ,const_cast,dynamic_cast等运算符不能重载。
类型转换运算符重载时,返回值类型不写,返回值类型就是类型本身。且不能有参数。
而= () [] ->只能重载为成员函数。

在上一节基础上补出两个运算符重载 “ - ” “ * ”

Time Time::operator-(const Time& t)const {

	int tot1, tot2;
	tot1 = t.minutes + t.hours * 60;
	tot2 = minutes + hours * 60;
	Time diff(abs(tot2 - tot1) / 60, abs(tot2 - tot1) % 60);
	return diff;
}

Time Time::operator*(double mult) const {

	long totalminutes = hours * mult * 60 + minutes * mult;
	Time result(totalminutes / 60, totalminutes % 60);
	return result;
}

至此我们可能还会觉得,每次都要调用Show()来将对象显示出来,实在是过于繁琐。如果能用最熟悉的左移运算符,岂不妙哉。
fair enough!
所以我们使用友元,让我们的**<<**可以输出Time对象,如下:

friend std::ostream & operator<<(std::ostream& os, const Time& t);
<-**************************************************************->
std::ostream& operator<<(std::ostream& os, const Time& t) {
	os << t.hours << "hours, " << t.minutes << "minutes";
	return os;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值