C++/重载关系运算符(5)
情景:
1 int a = 10; 2 int b = 10; 3 4 if(a==b) 5 { 6 cout<<"a和b相等"<<endl; 7 } 8 9 Person p1; 10 person p2; 11 12 if(p1==p2) //非内置数据类型关系运算符,编译器无法识别,须重载关系运算符 13 { 14 cout<<"a和b相等"<<endl; 15 } 16 17 if(p1!=p2) 18 { 19 cout<<"a和b不相等"<<endl; 20 }
重载关系运算符:
1 #include <iostream> 2 using namespace std; 3 4 class Person 5 { 6 public: 7 //有参构造函数 8 Person(string name, int age) 9 { 10 m_Name = name; 11 m_Age = age; 12 } 13 14 //重载==号 15 bool operator==(Person &p) 16 { 17 if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)//关键 18 { 19 return true; 20 } 21 return false; 22 } 23 24 //重载!=号 25 bool operator!=(Person &p) 26 { 27 if (this->m_Name == p.m_Name && this->m_Age == p.m_Age)//关键 28 { 29 return false; 30 } 31 return true; 32 } 33 34 string m_Name; 35 int m_Age; 36 37 }; 38 39 void test_01(void) 40 { 41 Person p1("Tom",18); 42 Person p2("Jerry", 18); 43 44 if (p1 == p2) 45 { 46 cout << "a和b相等" << endl; 47 } 48 else 49 { 50 cout << "a和b不相等" << endl; 51 } 52 53 if (p1 != p2) 54 { 55 cout << "a和b不相等" << endl; 56 } 57 else 58 { 59 cout << "a和b相等" << endl; 60 } 61 62 } 63 64 int main(void) 65 { 66 test_01(); 67 68 system("pause"); 69 return 0; 70 }