0

我有一个带有 3 个实例变量的基类 Person。Person(string name, unsigned long id, string email) 和一个继承 Person 并有一个新实例的派生类 Student var year Student(string name, unsigned long id,int year,string email): Person(name,id,email ) 和一位无需描述的班主任。

然后有一个名为 eClass 的类

我想重载比较运算符 == 并在编译我的 .cpp 时在函数 bool exists() 中使用该运算符我有那个错误

错误:无法在'eClass 中定义成员函数'Student::operator==' 任何人都可以帮助我吗?

我也不明白const

在我的代码的那个功能中。那是做什么的?

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;
   }
}
4

2 回答 2

2

您正在尝试在 eClass 中声明 Student 比较方法。您显示的 operator== 基本上应该属于 Student,而不是 eClass。在这种情况下, const 将保证指针不会以任何方式更改,当您希望简单地比较两个对象时绝对不希望这样做。

于 2012-12-11T22:44:06.533 回答
1

您应该将比较运算符移动到Student类中,仅使用引用(而不是对指针的引用),最后您在方法调用中缺少大括号

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

但是你真正应该做的是将比较运算符的一部分移到Person班级并在你的学生班级中使用它

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();
   }
};

在您的exists()方法中,您将指针与学生进行比较。您不需要比较运算符即可。

于 2012-12-11T23:26:34.480 回答