c++关系运算符重载
作者:互联网
关系运算符重载
判断是否相等运算符重载
operator(){}
--------------------------------------------------------
1 #include <iostream> 2 #include<string> 3 using namespace std; 4 5 class Persion//人 6 { 7 public: 8 Persion(string name, int age):m_Name(name),m_Age(age) 9 { 10 11 } 12 bool operator==(Persion &p)//判断是否相等运算符重载 13 { 14 if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) 15 { 16 return true; 17 } 18 else 19 { 20 return false; 21 } 22 } 23 string m_Name; 24 int m_Age; 25 }; 26 27 int main() 28 { 29 Persion p1("张三", 20); 30 Persion p2("李四", 23); 31 32 if (p1 == p2) 33 34 cout << "p1和p2相等 " << endl; 35 36 else 37 cout << "p1和p2不相等 " << endl; 38 39 40 system("pause"); 41 return 0; 42 }
--------------------------------------------------------
判断是否不相等
operator(){}
--------------------------------
1 #include <iostream> 2 #include<string> 3 using namespace std; 4 5 class Persion//人 6 { 7 public: 8 Persion(string name, int age) :m_Name(name), m_Age(age) {} 9 10 11 12 bool operator!=(Persion& p)//判断是否不相等运算符重载 13 { 14 if (this->m_Age == p.m_Age && this->m_Name == p.m_Name) 15 { 16 return false; 17 } 18 else 19 { 20 return true; 21 } 22 23 } 24 string m_Name; 25 int m_Age; 26 }; 27 28 int main() 29 { 30 Persion p1("张三", 20); 31 Persion p2("李四", 23); 32 33 if (p1 != p2) 34 35 cout << "p1和p2不相等 " << endl; 36 37 else 38 cout << "p1和p2相等 " << endl; 39 40 41 system("pause"); 42 return 0; 43 }
---------------------------------
>=运算符重载operator>=(){}
-----------------------------------
1 #include <iostream> 2 #include<string> 3 using namespace std; 4 5 class Persion//人 6 { 7 public: 8 Persion(string name, int age) :m_Name(name), m_Age(age) {} 9 10 11 12 bool operator>=(Persion& p)//判断是否大于等于运算符重载 13 { 14 if (this->m_Age >= p.m_Age && this->m_Name>= p.m_Name) 15 { 16 return true; 17 } 18 else 19 { 20 return false; 21 } 22 23 } 24 string m_Name; 25 int m_Age; 26 }; 27 28 int main() 29 { 30 Persion p1("张三", 20); 31 Persion p2("李四", 23); 32 33 if (p1 >= p2) 34 35 cout << "p1和p2不相等 " << endl; 36 37 else 38 cout << "p1和p2相等 " << endl; 39 40 41 system("pause"); 42 return 0; 43 }
-----------------------------------
<=运算符重载operator<=(){}
______________________________________
1 #include <iostream> 2 #include<string> 3 using namespace std; 4 5 class Persion//人 6 { 7 public: 8 Persion(string name, int age) :m_Name(name), m_Age(age) {} 9 10 11 12 bool operator<=(Persion& p)//判断是否小于等于运算符重载 13 { 14 if (this->m_Age <= p.m_Age && this->m_Name<= p.m_Name) 15 { 16 return true; 17 } 18 else 19 { 20 return false; 21 } 22 23 } 24 string m_Name; 25 int m_Age; 26 }; 27 28 int main() 29 { 30 Persion p1("张三", 20); 31 Persion p2("李四", 23); 32 33 if (p1 <= p2) 34 35 cout << "p1和p2不相等 " << endl; 36 37 else 38 cout << "p1和p2相等 " << endl; 39 40 41 system("pause"); 42 return 0; 43 }
_______________________________________
可以让两个自定义类型对象进行对比操作
标签:Name,int,Age,c++,运算符,重载,Persion,include,name 来源: https://www.cnblogs.com/putobit/p/14412925.html