【问题标题】:Overloading the comparison operators == C++重载比较运算符 == C++
【发布时间】:2012-12-11 22:39:35
【问题描述】:

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

然后有一个名为 eClass 的类

我想重载比较运算符 == 并使用该运算符 在函数布尔存在() 当我编译我的 .cpp 我有那个错误

错误:无法在'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;
   }
}

【问题讨论】:

    标签: c++ compiler-errors operator-overloading comparator


    【解决方案1】:

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

    【讨论】:

    • 这不是正确的const。这意味着作为this 传入的对象除了其mutable 成员之外不会被修改,这仍然可以。
    • 另外,运算符是C++中的保留字
    【解决方案2】:

    您应该将比较运算符移动到 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 类并在您的 Student 类中使用它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-06-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-07
      • 2011-08-12
      相关资源
      最近更新 更多