关系运算符==
1、C++中定义相等运算符,它们会比较对象的每一个数据成员,只有当所有对应的成员都相等时才认为两个对象相等。代码如下:
class Person
{
public:
Person(string name, int age)
{
this->m_Name = name;
this->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;
}
}
bool operator!=(Person& p)
{
if (this->m_Name != p.m_Name || this->m_Age != p.m_Age)
{
return true;
}
else
{
return false;
}
}
public:
string m_Name;
int m_Age;
};
2、测试函数①
Person p1("牛魔王", 180);
Person p2("牛魔王", 180);
if (p1 == p2)
{
cout << "p1和p2是相等的!" << endl;
}
else
{
cout << "p1和p2是不相等的!" << endl;
}
测试结果
p1和p2是相等的!
请按任意键继续. . .
3、测试函数②
Person p1("孙悟空", 180);
Person p2("孙悟空", 200);
if (p1 != p2)
{
cout << "p1和p2不相等!" << endl;
}
else
{
cout << "p1和P2相等!" << endl;
}
测试结果
p1和p2不相等!
请按任意键继续. . .