Operator overloading

I keep getting errors from trying to set up a operator overloading function. The gist of the program is to sort arrays of two different data structures, by comparing a specif member of said structures. I have no idea what's wrong this is my first time using member functions/operator overloading.

functs.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
...
bool operator>(const Trashpile& lhs, const Trashpile& rhs)
{
  return lhs.weight > rhs.weight;
}
bool operator>(const Offender& lhs, const Offender& rhs)
{
  return lhs.guilt > rhs.guilt;
}
void Trashpile::operator=(const Trashpile& rhs)
{
    (*this).sector_num = rhs.sector_num;
    (*this) = rhs.weight;
    return;
}
void Offender::operator=(const Offender& rhs)
{
    (*this).name = rhs.name;
    (*this).guilt = rhs.guilt;
    return;
}
...


functs.h
1
2
3
4
5
6
...
bool operator>(const Trashpile& lhs, const Trashpile& rhs);
bool operator>(const Offender& lhs, const Offender& rhs);
void Trashpile::operator=(const Trashpile& rhs);
void Offender::operator=(const Offender& rhs);
...


array.h
1
2
3
4
5
6
7
8
9
10
11
struct Trashpile
{
    int weight;
    int sector_num;
};

struct Offender
{
    int guilt;
    string name;
};


templates.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
...
template <typename T>
void sortArray(T & SArray, int size)
{
    T temp;
    for (int i =0; i < size; i++)
    {
        for(int j = 0; j < (size-1); j++)
        {
            if(SArray[j] > SArray[j+1])
            {
                T temp = SArray[j+1];
                SArray[j+1] = SArray[j];
                SArray[j] = temp;
            }
        }
    }
}
...




Last edited on
What is the error?

Note that the prototype

bool operator>(const Trashpile& lhs, const Trashpile rhs); // Note: missing &

does not match the implementation

1
2
3
4
  bool operator>(const Trashpile& lhs, const Trashpile& rhs)
{
  return lhs.weight > rhs.weight;
}


Is that the problem?
A few problems in sortArray().

templates.hpp
-------------
line 3: SArray is passed by value. The function is operating on a copy of the array. The sorted copy goes out of scope when the function exits. SArray should be passed by reference.

Lines 6,8: The termination condition of your for loops are incorrect. They should be:
i<size

Lines 10,12,13: Are going to cause an out of bounds condition. j+1 is going to be out of bounds on the last iteration of the inner loop.

I applied those fixes.
I'm getting errors retaining to the assignment (=) operation overload.

Error:Prototype for 'void Trashpile::operator=(const Trashpile& rhs)' does not match any in class
Error: candidate is: void Trashpile::operator=(const Trashpile& rhs)
The operator=(...) must be declared within the class/struct, not outside.

However it is not necessary since an appropriate operator= will be generated by the compiler.
Topic archived. No new replies allowed.