C++ 125类和对象_运算符重载_关系
学习内容
判断两个自定义对象是否相等、不相等
结果
代码
#include<iostream>
using namespace std;//cout 在这里,没有它会报错
#include<string>
//类和对象_运算符重载_关系运算符
//学习内容
//判断两个自定义对象是否相等、不相等
class Person
{
public:
Person(string name,int age)
{
m_Name = name;
m_Age = age;
}
string m_Name;
int m_Age;
/// <summary>
/// 关系运算符 == 重载
/// 其他 >=,<= ,>,< , != 都是一样的
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
bool operator==(Person& p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return true;
}
else
{
return false;
}
}
/// <summary>
/// 关系运算符 != 重载
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
bool operator!=(Person& p)
{
if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
{
return false;
}
else
{
return true;
}
}
};
void test02()
{
Person p1("cjh", 18);
Person p2("cjh", 18);
cout << "年龄:" << p1.m_Age << endl;
cout << "年龄:" << p2.m_Age << endl;
cout << "P1 是否相等 P2:" << ((p1 == p2)?"是,相等":"否,不相等") << endl;
cout << "P1 是否不相等 P2:" << ((p1 != p2) ? "是,不相等" : "否,相等") << endl;
}
int main()
{
test02();
system("pause");
}