--->让2个自定义类型进行对比操作
一.用等号重载
//赋值运算符重载
#include <iostream>
using namespace std;
class Person
{
public:
Person(string name,int age)
{
m_Name = name;
m_Age = age;
}
bool operator==(Person& p)//赋值运算符重载(重载==号)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
return true;
else
return false;
}
private:
string m_Name;
int m_Age;
};
void test01()
{
Person p1("张三", 16);
Person p2("李四", 17);
if (p2 == p1)
{
cout << "相等" << endl;
}
else
{
cout << "不相等" << endl;
}
}
int main()
{
test01();
return 0;
}
二.用不等号重载
#include <iostream>
using namespace std;
class Person
{
public:
Person(string name,int age)
{
m_Name = name;
m_Age = age;
}
bool operator!=(Person& p)//赋值运算符重载(重载==号)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
return false;
else
return true;
}
private:
string m_Name;
int m_Age;
};
void test01()
{
Person p1("张三", 16);
Person p2("李四", 17);
if (p2 != p1)
{
cout << "不相等" << endl;
}
else
{
cout << "相等" << endl;
}
}
int main()
{
test01();
return 0;
}