C++运算符重载——重载限制 及 重载输出类对象
日期: 2020-06-13 分类: 跨站数据测试 290次阅读
使用运算符时,不能违反原来的语法规则,不能修改优先级
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
标签:C++
精华推荐