首页 > 解决方案 > C++ 必须接受一个或零个参数错误 (Operator+)

问题描述

我的 Hour.cpp 文件中有以下语句:(课后时间)

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

标签: c++operator-keyword

解决方案


在将运算符重载为成员函数时,您只能将另一个类作为第二个操作数。第一个操作数是类本身的对象。所以,你有两个选择:

  • 您可以将重载函数修改为
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());
}

推荐阅读