我的 Hour.cpp 文件中有以下语句:(课后 Hour)
Hour Hour ::operator+(const Hour& h1, const Hour& h2) const{
return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond());
}
但是,运行后我得到:
error: must take either zero or one argument
在将运算符重载为成员函数时,您只能将另一个类作为第二个操作数。第一个操作数是类本身的对象。所以,你有两个选择:
Hour Hour::operator+(const Hour& h) const{
return Hour(hour_ + h.getHour(), minute_ + h.getMinute(), seconds_ + h.getSecond());
}
where hour_, minute_, seconds_ are member variables of Hour class.
Hour operator+(const Hour& h1, const Hour& h2) const{
return Hour(h1.getHour()+ h2.getHour(), h1.getMinute() + h2.getMinute(), h1.getSecond() + h2.getSecond());
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句