2

I am trying to compare two arrays by making an overloaded operator ==. My code looks something like this:

//myArray.h
class myArray {
    int size, start, end;
    int *data;

public:
    myArray(int sz);
    myArray(int lower, int upper);
    int &operator [](const int index);
    bool operator == (const myArray& index);
};

//myArray.cpp
bool operator == (const myArray& index);
{

}

but there is an error in my cpp file where it says:

too few parameters for this operator function, Function definition for 'operator==' not found.

Any advice/solutions to this error would be much appreciated!

AbdelAziz AbdelLatef
  • 3,650
  • 6
  • 24
  • 52
NetElvis
  • 15
  • 1
  • 2
  • 1
    Your implementation of `operator==` is a free function, not the one your class declared. – jkb Oct 12 '19 at 19:43
  • Another recommendation: use `std::size_t` for indices and sizes instead of `int`, as it will always be large enough to represent the maximum number of elements possible on the given platform. E.g. on AMD64, `int` is typically 32bit, but arrays can be larger than 2^32 elements. – Erlkoenig Oct 13 '19 at 10:10

2 Answers2

3

You have 2 problems with this line right here:

//myArray.cpp
bool operator == (const myArray& index);

The first problem is trivial. There is no need for the ; in this context. In fact, putting one there could cause an error.

The second, somewhat more serious one is the fact that operator==() is a member function of myArray. Thus, you need to preface the definition with the class name just like any other member function:

//myArray.cpp
bool myArray::operator == (const myArray& index) 

Should work fine.


Also worth noting is that if you didn't want it to be a member function (which you seem to want, but just in case), you could do this instead:

//myArray.cpp
bool operator == (const myArray& lhs, const myArray& rhs)
{

}

Then change your declaration to this instead:

friend bool operator == (const myArray& lhs, const myArray& rhs);
0

operator== in myArray.cpp is distinct from operator== in myArray.h. The latter is a member function of class myArray, the former is a standalone non-member function.

The member function form of operator== takes one parameter (which is compared to *this). The non-member form takes two parameters (which are compared one to the other). Figure out which one you want, and stick to it.

Igor Tandetnik
  • 50,461
  • 4
  • 56
  • 85