重载==运算符:
//重载 == 号运算符
bool operator == (Person & p)
{
if (this->m_name == p.m_name && this->m_age == p.m_age)
{
return true;
}
return false;
}
重载!=运算符:
//重载 != 号运算符
bool operator != (Person& p)
{
if (this->m_name != p.m_name && this->m_age != p.m_age)
{
return true;
}
return false;
}
完整代码:
#include <iostream>
using namespace std;
#include <string>
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;
}
return false;
}
//重载 != 号运算符
bool operator != (Person& p)
{
if (this->m_name != p.m_name && this->m_age != p.m_age)
{
return true;
}
return false;
}
string m_name;
int m_age;
};
//调用
void test01()
{
Person p1("Tom", 18);
Person p2("Tom", 18);
if (p1 == p2)
{
cout << "p1 == p2" << endl;
}
else
{
cout << "p1 != p2" << endl;
}
if (p1 != p2)
{
cout << "p1 != p2" << endl;
}
else
{
cout << "p1 == p2" << endl;
}
}
int main() {
test01();
system("pause");
return 0;
}