【问题标题】:C++ Must take either one or zero argument error (Operator+)C++ 必须接受一个或零个参数错误 (Operator+)
【发布时间】:2021-11-17 21:08:06
【问题描述】:

我的 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

【问题讨论】:

  • 因为您将operator+ 实现为成员,所以第一个操作数是this,因此第二个操作数只需要一个参数。

标签: c++ operator-keyword


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2012-11-12
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    • 2021-10-29
    • 1970-01-01
    • 2014-06-13
    • 1970-01-01
    相关资源
    最近更新 更多