Tag Archives: must take either zero or one argument

[Solved] Operator overload must take either zero or one argument error

When writing class objects (I used structs), operator overloading is used. At this time, there is a problem. An error is always reported during compilation: item:: operator + (const item & amp;);, const item&)’ must take either zero or one argument;

Code here:

struct item{
    int a,b;
    item(int _a=0,int _b=0):a(_a),b(_b){};
    item operator - (const item& c);
    item operator + (const item& _a,const item& _b);
};
item item::operator - (const item& c){
    return item(a-c.a,b-c.b);
}
item item::operator + (const item& _a,const item& _b){
    return item(_a.a+_b.a,_a.b+_b.b);
}

There are too many parameters when the operator is overloaded as a member function

Two parameter member functions (addition) can be changed to global variables or single parameter global variables (such as subtraction)

Because when called, “A-B” is understood by the compiler as

a.operator - (b)

Therefore, when the operator is overloaded as a member function, the number of parameters should be the number of operators minus one; When overloaded as a global function, it is equal to the number of entries of the operator

The modification code is as follows:

struct item{
    int a,b;
    item(int _a=0,int _b=0):a(_a),b(_b){};
    item operator - (const item& );
};
item item::operator - (const item& c){
    return item(a-c.a,b-c.b);
}
item operator + (const item& A,const item& B){
    return item(A.a+B.a,A.b+B.b);
}