Question

I am currently working on creating an overloaded function for the == operator. I am creating an hpp file for my linked list and I can't seem to get this operator working 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 function body
C2143: syntax error : missing ';' before '*'
C4430: missing type specifier - int assumed. Note: C++ does not support default-int

I've tried changing things around but I constanly get the same errors as above

Any tips or assistance on this is greatly appreciated.

Was it helpful?

Solution

The member operator only has one argument, which is the other 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 doesn't actually make sense, since it just calls itself recursively. Instead, it should be calling some member operation, like return this->impl == rhs.impl;.

OTHER TIPS

You are declaring the == overload as part of the class definition, as a method instances will get. Thus, the first parameter you request, lhs, is already implicit: remember, within an instance's 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 to others".

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

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

The comparison operators are very simple. Define == first, using a function signature like this:

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

HOW to compare MyClass objects is all your own.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top