Overloading the comparison operators == C++

2019-09-05 05:26发布

问题:

I have a base class Person with 3 instance vars. Person(string name, unsigned long id, string email) and one derived class Student that inherits Person and have one new instance var year Student(string name, unsigned long id,int year,string email): Person(name,id,email) and one class Teacher that isn't necessary to describe.

Then a have the class named eClass

and I want Overload the comparison operator == and use that operator in function bool exists() when I compile my .cpp i have that error

error: cannot define member function 'Student::operator==' within'eClass can anyone help me with that?

Also I don't understand the const

in that function of my code. what that do?

bool Student::operator==(const Student* &scnd)const{... ... ...}

eClass{
  private:
  Teacher* teacher;
  string eclass_name;
  Student* students[MAX_CLASS_SIZE];
  unsigned int student_count;

   public:
   eClass(Teacher* teach, string eclsnm){
   teacher=teach;
   eclass_name=eclsnm;
  }
   bool Student::operator==(const Student* &scnd)const{
         return(getID==scnd.getID
         &&getName==scnd.getName
         &&getYear==scnd.getYear
         &&getEmail==scnd.getEmail);

   }
   bool exists(Student* stud){
       for(int i=0; i<MAX_CLASS_SIZE;++i){
       if(stud==students[i]){return TRUE;}
       }
       return FALSE;
   }
}

回答1:

You're trying to declare a Student comparison method within eClass. The operator== you showed should basically belong to Student, not eClass. The const in this case will guarantee you that the pointer will not be changed in any way, which is definitely not wanted when you wish to simply compare two objects.



回答2:

You should move the comparison operator into the Student class, use a reference only (not reference to pointer) and finally you're missing the braces at the method calls

class Student : public Person {
public:
   bool operator==(const Student &scnd)const{
         return getID()==scnd.getID()
         && getName()==scnd.getName()
         && getYear()==scnd.getYear()
         && getEmail()==scnd.getEmail();
   }
};

But what you really should do, is move part of the comparison operator to the Person class and use this in your Student class

class Person {
public:
   bool operator==(const Person &scnd)const{
         return getID()==scnd.getID()
         && getName()==scnd.getName()
         && getEmail()==scnd.getEmail();
   }
};

class Student : public Person {
public:
   bool operator==(const Student &scnd)const{
         return Person::operator==(scnd)
         && getYear()==scnd.getYear();
   }
};

In your exists() method you compare pointers to Students. You don't need a comparison operator for this to work.