C++ //关系运算符重载 < = > !=

 1 //关系运算符重载 < = > !=
 2 #include <iostream>
 3 #include <string>
 4 using namespace std;
 5 
 6 
 7 //重载关系运算符
 8 class Person
 9 {
10 public:
11     Person(string name, int age)
12     {
13         m_Name = name;
14         m_Age = age;
15     }
16 
17 
18     //重载 == 号
19     bool operator==(Person& p)
20     {
21         if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
22         {
23             return true;
24         }
25         return false;
26     }
27 
28 
29     bool operator !=(Person& p)
30     {
31         if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)
32         {
33             return false;
34         }
35         return true;
36     }
37 
38     string m_Name;
39     int m_Age;
40 
41 
42 };
43 
44 void test01()
45 {
46     Person p1("Tom", 18);
47 
48     Person p2("Tom", 20);
49 
50     if (p1 == p2)
51     {
52         cout << "p1和 p2 是相等的!" << endl;
53     }
54     else
55     {
56         cout << "p1和 p2 是不不不不相等的!" << endl;
57     }
58 
59 
60     if (p1 !=p2)
61     {
62         cout << "p1和 p2 是不相等的!" << endl;
63     }
64     else
65     {
66         cout << "p1和 p2 是相等的!" << endl;
67     }
68 }
69 
70 int main()
71 {
72     test01();
73 }

 

posted on 2021-08-07 17:17  Bytezero!  阅读(145)  评论(0编辑  收藏  举报