利用 operator实现==重载,实现两个类进行比较
1.不带参数的函数
#include <iostream>
#include <string>
using namespace std;class Person // 1.定义一个类
{
public:Person(string name, int age){this->name = name;this->age = age;}bool operator==(Person &p) // 2.定义一个operator== {if (this->age = p.age && this->name == p.name)return true;return false;}string name;int age;
};void test() // 3.定义一个无参数的函数
{ // 实例化,两个类对象p1,p2。Person p1("xixi", 24); Person p2("nini", 30);if (p1 == p2){cout << "it is true!" << endl;}else{cout << "it is false!!" << endl;}
}int main() // 4.调用函数,比较
{test();system("pause");return 0;
}
2.带参数的函数
#include <iostream>
#include <string>
using namespace std;class Person // 1.定义一个类
{
public:Person(string name, int age){this->name = name;this->age = age;}bool operator==(Person &p) // 2.定义一个operator== {if (this->age = p.age && this->name == p.name)return true;return false;}string name;int age;
};void test(Person a, Person b) // 3.定义一个带类对象的函数
{ if (a == b){cout << "it is true!" << endl;}else{cout << "it is false!!" << endl;}
}int main()
{// 4.实列化两个对象Person p1("xixi", 24); Person p2("nini", 30);// 5.调用函数,实现两个类比较test(p1,p2); system("pause");return 0;
}