Young87

SmartCat's Blog

So happy to code my life!

游戏开发交流QQ群号60398951

当前位置:首页 >跨站数据测试

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;
}

除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog

上一篇: 千万别再一直无脑使用ES6的箭头函数了,它虽然很有用但并不是万能的

下一篇: 怒肝俩月,新鲜出炉史上最有趣的Java小白手册,第一版,每个 Java 初学者都应该收藏

精华推荐