C++Note 运算符重载 关系运算符

关系运算符

作用:重载关系运算符,可以让两个自定义类型对象进行对比操作

 

 1 #include <iostream>
 2 using namespace std;
 3 //重载关系运算符
 4 class Person
 5 {
 6 public:
 7     Person(string name, int age)
 8     {
 9         m_Name = name;
10         m_Age = age;
11     }
12     bool operator== (Person& p)//!=与==相反
13     {
14         if (this->m_Age == p.m_Age && this->m_Name == p.m_Name)
15             return true;
16         else
17             return false;   
18     }
19     string m_Name;
20     int m_Age;
21 };
22 void test()
23 {
24     Person p1("s1", 11);
25     Person p2("s1", 12);
26     if (p1 == p2)
27         cout << "p1 and p2 是相等的" << endl;
28     else
29         cout << "p1 and p2 是不相等的" << endl;
30 }
31 int main()
32 {
33     test();
34     system("pause");
35     return 0;
36 }

 

posted on 2023-07-12 11:15  廿陆  阅读(17)  评论(0)    收藏  举报

导航