重载比较运算符== C ++ [英] Overloading the comparison operators == C++

查看:89
本文介绍了重载比较运算符== C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个具有3个实例变量的基类Person. 人(字符串名称,未签名的长ID,字符串电子邮件) 一个继承人的派生班学生 并有一个新实例var year 学生(字符串名称,未签名的长ID,年份,字符串电子邮件):人员(名称,ID,电子邮件) 还有一个不需要描述的班级老师.

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.

然后有一个名为eClass的类

Then a have the class named eClass

,我想重载比较运算符==并使用该运算符 在功能布尔存在() 当我编译我的.cpp文件时,我遇到了这个错误

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

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

我也不理解 const

在我的代码的功能中.怎么办?

in that function of my code. what that do?

bool Student :: operator ==(const Student *& scnd) 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;
   }
}

推荐答案

您正在尝试在eClass中声明一个Student比较方法.您显示的运算符==应该基本上属于Student,而不是eClass.在这种情况下,const可以保证您不会以任何方式更改指针,当您只想比较两个对象时绝对不需要.

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.

这篇关于重载比较运算符== C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆