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);
}
Similar Posts:
- [Solved] Error: error c2678: binary ‘<', no left operand operator (or no acceptable conversion) that accepts type 'const a' was found
- C++ error: cannot bind non-const lvalue reference of type ‘myString&’ to an rvalue of type ‘m…
- error: no match for ‘operator<' (operand types are 'const Request_Info' and 'const Request_Info')xxxxxxx
- C++ Error: passing ” “as” ” discards qualifiers
- Oracle ORA-00936: missing expression [How to Solve]
- [swscaler @ …] deprecated pixel format used, make sure you did set range correctly
- The applet reports an error thirdscripterror DateValue is not defined;
- invalid conversion from ‘void* (*)()’ to ‘void* (*)(void*)’
- Error reporting on data type and matrix dimension of eigen
- [Solved] ant Error: Cannot use ‘in’ operator to search for ‘value’ in undefined