c++ - 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
解决方案
在将运算符重载为成员函数时,您只能将另一个类作为第二个操作数。第一个操作数是类本身的对象。所以,你有两个选择:
- 您可以将重载函数修改为
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());
}
推荐阅读
- android - 如何将现有的 sqlite 数据库添加到 Flutter 并打印为卡片列表?
- javascript - PayPal 结帐与 JS SDK 按钮的集成 - “无效 sdk 元”的问题
- python - SVC 无法解决 MNIST
- java - launch4j:java.lang.OutOfMemoryError:超出 GC 开销限制
- postgresql - 存储过程(或更好的方法)每天 22:00 向现有表添加新行
- arrays - BigQuery 类型:如何定义任何类型的数组?
- python-3.x - 预期类型“dict”,用于“str”而不是 PyCharm。尝试使用表格将所有 PDF 页面转换为 CSV?
- angular - 没有(点击)功能的角度加载图像
- opencv - 有没有办法从 OpenCV 中的霍夫的 Trasnform 中提取单行?
- tensorflow - Conv2D keras 中的正则器