重载比较运算符 == C++

Overloading the comparison operators == C++

本文关键字:C++ 运算符 比较 重载      更新时间:2023-10-16

我有一个带有 3 个实例变量的基类 Person。人员(字符串名称、未签名长 ID、字符串电子邮件)和一个派生类 继承 Person 的学生并有一个新的实例 var 年学生(字符串名称,未签名的长ID,int年份,字符串电子邮件):人(姓名,ID,电子邮件)还有一个班主任,不需要描述。

然后有一个名为 eClass 的类

我想要重载比较运算符 == 并使用该运算符在函数中布尔存在()当我编译.cpp时出现该错误

错误:无法在"eClass"中定义成员函数"学生::运算符=="谁能帮我?

我也不明白常量

在我的代码的那个函数中。那有什么作用?

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

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

您应该

将比较运算符移动到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()方法中,您将指针与学生进行比较。您不需要比较运算符即可正常工作。