运算符重载-关系运算符重载
关系运算符的重载,可以让两个自定义对象进行对比操作
重载==号,当姓名和年龄相等时才相等
#include<iostream>
using namespace std;
//关系运算符重载
class Person
{
public:
Person(string name,int age) {
mname = name;
mage = age;
}
//重载==号
bool operator==(Person& p)
{
if (this->mname == p.mname && this->mage == p.mage) {//姓名和年龄相等时,才相等
return true;
}
return false;
}
string mname;
int mage;
};
void test01() {
Person p1("Lily", 18);
Person p2("Lily", 18);
if (p1 == p2)
{
cout << "p1和p2相等" << endl;
}
else
{
cout << "p1和p2不相等" << endl;
}
}
int main() {
test01();
system("pause");
return 0;
}
在运行程序时,由于还有赋值运算符的那个文件,报错了,解决方案如下:
1.选中赋值运算符重载的属性
2.从生成中排除,选择是
3.此时不报错了,可以看运行结果了