error C2804:binary 'operator +' has too many parameters

来源:清泛原创     2016-08-29 17:09:19    人气:     我有话说( 0 人参与)

error C2804:binary &#39;operator +&#39; has too many parameters代码如下:#include <iostream> #include <string> clas...

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 C2804

注:本文为本站或本站会员原创优质内容,版权属于原作者及清泛网所有,
欢迎转载,转载时须注明版权并添加来源链接,谢谢合作! (编辑:admin)
分享到: