#include <iostream>
#include <string>
using namespace std;
/************************************************************************
关系运算符重载 == 、!=
/************************************************************************/
class Person{
public:
//有参构造
Person(int age, char* name)
{
m_age = age;
m_name = new char[strlen(name)+1];
strcpy(m_name, name);
}
//关系运算符==重载
bool operator==(const Person &per)
{
if (m_age == per.m_age && strcmp(m_name, per.m_name) == 0)
{
return true;
}
return false;
}
//关系运算符!=重载
bool operator!=(const Person &per)
{
if (m_age != per.m_age || strcmp(m_name, per.m_name) != 0)
{
return true;
}
return false;
}
~Person()
{
if (m_name != NULL)
{
delete m_name;
m_name = NULL;
}
}
private:
int m_age;
char *m_name;
};
void test1()
{
Person per1(20, "Tom");
Person per2(20, "Jerry");
if (per1 == per2)
{
cout<<"per1和per2相等"<<endl;
}
if (per1 != per2)
{
cout<<"per1和per2不相等"<<endl;
}
}
int main()
{
test1();
return 0;
}
C++ 关系运算符重载
最新推荐文章于 2023-08-19 21:55:28 发布