Overload operator == complains about 'must take exactly one argument'

I try to overload operator== , but the compiler throws the following error:

 'bool Rationalnumber::operator==(Rationalnumber, Rationalnumber)' must take exactly one argument 

My short piece of code is as follows:

 bool Rationalnumber::operator==(Rationalnumber l, Rationalnumber r) { return l.numerator() * r.denominator() == l.denominator() * r.numerator(); } 

Declaration:

 bool operator==( Rationalnumber l, Rationalnumber r ); 

Does anyone have any idea why he is throwing a mistake?

+6
source share
5 answers

If operator== is a non-stationary data element, it should take only one parameter, since the comparison will be with the implicit this parameter:

 class Foo { bool operator==(const Foo& rhs) const { return true;} }; 

If you want to use a free operator (i.e. not a member of a class), you can specify two arguments:

 class Bar { }; bool operator==(const Bar& lhs, const Bar& rhs) { return true;} 
+12
source

As a member operator overload, it should only take one argument and the other this .

 class Foo { int a; public: bool operator==(const Foo & foo); }; //... bool Foo::operator==(const Foo & foo) { return a == foo.a; } 
+2
source

You must remove your == operator from RationalNumber to another location. Since it is declared inside the class, it is considered that 'this' is the first argument. From the semantics, you can see that you offer 3 arguments to the compiler.

+1
source
 friend bool operator==( Rationalnumber l, Rationalnumber r ); 

when you declare it as a function other than a member, it can take two arguments. when you declare it as a member function, it can take only one argument.

0
source

If you declare const SpreadSheetCell & operator + (const SpreadSheetCell & lhs, const SpreadSheetCell & rhs); then the first argument acts as a pointer to "this". So enter the error as ".

error: 'const SpreadSheetCell & SpreadSheetCell :: operator + (const SpreadSheetCell &, const SpreadSheetCell &)' must accept either zero or one argument.

If you want to have a function of two arguments, then you must declare the same function outside the class and use it.

0
source

Source: https://habr.com/ru/post/919142/


All Articles