重载比较运算符 == C++
Overloading the comparison operators == C++
我有一个带有 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()
方法中,您将指针与学生进行比较。您不需要比较运算符即可正常工作。
相关文章:
- 为什么比较运算符如此快速
- C++映射:具有自定义类的运算符[]不起作用(总是返回0)
- 使用C++中的模板和运算符重载执行矩阵运算
- 为什么这个运算符<重载函数对 STL 算法不可见?
- 增量运算符与后缀混淆
- 一个关于在C++中重载布尔运算符的问题
- 运算符C++ "delete []"仅删除 2 个前值
- 模板类无法识别友元运算符
- 我可以使用条件运算符初始化C风格的字符串文字吗
- 关闭||运算符优化
- 通过继承类使用来自不同命名空间的运算符
- C++Cast运算符过载
- 如何使用AngelScript注册SFML Vector2运算符
- 重载元组索引运算符-C++
- 如何使用重载的相等(==)运算符向测试用例添加描述
- 为什么Mat类的两个对象可以在不重载运算符+的情况下添加
- 多个If语句与使用逻辑运算符计算条件的单个语句的比较
- 布尔比较运算符是如何在C++中工作的
- 重载运算符new[]的行为取决于析构函数
- 如何防止clang格式在流运算符调用之间添加换行符<<