error C2804:binary 'operator +' has too many parameters
清泛原创
error C2804:binary 'operator +' has too many parameters
代码如下:
#include <iostream>
#include <string>
class Sales_item
{
// private members
private:
std::string isbn;
unsigned units_sold;
double revenue;
//public method
public:
..
//Overloaded Operator as member function
Sales_item& operator+=(const Sales_item&);//Compound Assignment Operators
Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs);
};
// implement file Sales_item.cpp
using std::istream;
using std::ostream;
//Overloaded Operator as nonmember functions
inline Sales_item Sales_item::operator+(const Sales_item& lhs, const Sales_item& rhs)
{
Sales_item ret(lhs); // copy lhs into a local object that we'll return
ret += rhs; // add in the contents of rhs
return ret; // return ret by value ,not by reference
}
解决方法:+操作符包括两个操作数,应该重载为普通非成员函数。
注意重载操作符的形参数目(包括成员函数的隐式 this 指针)与操作符的操作数数目相同。对称的操作符,如算术操作符、相等操作符、关系操作符和位操作符,最好定义为普通非成员函数。因此+应该重载为普通非成员函数。这里重载为成员函数时多了一个this形参,故对于+操作符来说,出现参数过多的错误。
即书写为:
// header file
Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs);
//implement file
//Overloaded Operator as nonmember functions
inline Sales_item operator+(const Sales_item& lhs, const Sales_item& rhs)
{
Sales_item ret(lhs); // copy lhs into a local object that we'll return
ret += rhs; // add in the contents of rhs
return ret; // return ret by value ,not by reference
}
上一篇:error C2780: 'void __cdecl std::sort(_RI,_RI,_Pr)' : expects 3 arguments - 2 provided
下一篇:error C2872: “count”: 不明确的符号