Function overload ==

I am currently working on creating an overloaded function for the == operator. I am creating an hpp file for a linked list, and I cannot get this statement to work in the hpp file.

I currently have this:

template <typename T_> class sq_list { bool operator == ( sq_list & lhs, sq_list & rhs) { return *lhs == *rhs; }; reference operator * () { return _c; }; }; } 

I get about 10 errors, but they pretty much repeat as errors:

C2804: binary 'operator ==' has too many parameters
C2333: 'sq_list :: operator ==': error in function declaration; skipping body function
C2143: syntax error: missing ';' before '*'
C4430: missing type specifier - int. Note: C ++ does not support default-int

I tried to make a difference, but I constantly get the same errors as above

Any advice or help on this subject is welcome.

+7
source share
3 answers

A member statement has only one argument, which is another object. The first object is the instance itself:

 template <typename T_> class sq_list { bool operator == (sq_list & rhs) const // don't forget "const"!! { return *this == *rhs; // doesn't actually work! } }; 

This definition does not really make sense, because it simply calls itself recursively. Instead, it should invoke some member operation, for example return this->impl == rhs.impl; .

+7
source

You declare overload == as part of the class definition, as instances of the method will receive. So the first parameter you request, lhs , is already implicit: remember, as part of the instance methods, you have access to this .

 class myClass { bool operator== (myClass& other) { // Returns whether this equals other } } 

The operator == () method as part of a class should be understood as "this object knows how to compare itself with others."

You can overload operator == () outside the class to get two arguments, both objects being compared if that makes more sense to you. Take a look here: http://www.learncpp.com/cpp-tutorial/94-overloading-the-comparison-operators/

0
source

http://courses.cms.caltech.edu/cs11/material/cpp/donnie/cpp-ops.html

Comparison operators are very simple. First define == using the function signature as follows:

  bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. } 

HOW to compare MyClass objects - all your own.

0
source

All Articles