重载运算符 支持Student对象和Worker对象判断对象是否相等的运算,即==运算符,ID相等即认为是相等。
时间: 2024-05-05 09:21:17 浏览: 41
重载运算符
可以在Student类和Worker类中分别重载==运算符,代码示例如下:
```c++
class Student {
public:
int id;
bool operator==(const Student& other) const {
return id == other.id;
}
};
class Worker {
public:
int id;
bool operator==(const Worker& other) const {
return id == other.id;
}
};
```
这样就可以使用==运算符判断两个对象是否相等了,例如:
```c++
Student s1 = {1};
Student s2 = {2};
Worker w1 = {1};
Worker w2 = {2};
if (s1 == s2) {
cout << "s1 and s2 are equal" << endl;
} else {
cout << "s1 and s2 are not equal" << endl;
}
if (w1 == w2) {
cout << "w1 and w2 are equal" << endl;
} else {
cout << "w1 and w2 are not equal" << endl;
}
if (s1 == w1) {
cout << "s1 and w1 are equal" << endl;
} else {
cout << "s1 and w1 are not equal" << endl;
}
```
输出结果为:
```
s1 and s2 are not equal
w1 and w2 are not equal
s1 and w1 are equal
```
阅读全文