0
votes

I have a class called "Students" one of the variables is a string that contains the student's name.

I want to overload the ">" operator so it tests to see if the first student's name is longer than the second student's name and I want it to return a bool (true or false) value.

bool operator>(Students student1, Students student2)
{ //code to compare the two strings}

I keep getting an error that says I have too many parameters.

2
It would be bad idea to implement such overload (because you may want to compare the objects by age later). Implement instead name_comparator class template. Likewise, age_comparator if you need later! - Nawaz
@Nawaz: sounds like overengineering. Why not just compare the names' lengths where such a comparison is needed? - Fred Foo
I agree that this is a bad idea from "go," but beyond that if you need help with errors you're getting, then we will need to see those errors and the code that generated them at least. - John Dibling
You probably declared it as a member function. It should be a non-member. - juanchopanza

2 Answers

1
votes

You do have too many parameters.

When overloading an operation, the first, implicit parameter is the current object, also called this.

So you want:

class Students
{
    /*Param #1 is THIS*/ 
    bool operator>(Students& student2)
    {
        return (this->name.Length > student2.name.Length);
    }
}

And the usage will be something like:

void MyFunc()
{
    Students alpha("Eric");
    Students beta("Sampson");

    if (alpha > beta) // effectively calls alpha.OperatorGreater(alpha, beta)

}
0
votes

Declare comparison operator either as non-member or member function. See the following examples, both of which work just fine.

Non-member function version:

using namespace std;

struct s {
  double a;
  s(double aa): a(aa) {};
};

bool operator< (const s &s1, const s &s2) {
  return s1.a < s2.a;
}

int main() {
  s s1(1);
  s s2(2);

  bool b = s1 < s2;
}

Member function version:

using namespace std;

struct s {
  double a;
  s(double aa): a(aa) {};

  bool operator< (const s &s2) { return a < s2.a ;}
};


int main() {
  s s1(1);
  s s2(2);

  bool b = s1 < s2;
}