简单函数模板和“==”运算符重载


1 #include<iostream> 2 using namespace std; 3 //创建一个Person类 4 class Person 5 { 6 public: 7 Person(int age1, string name1) 8 { 9 this->age = age1; 10 this->name = name1; 11 } 12 int age; 13 string name; 14 };
//方法一:利用运算符重载进行比较 15 //“==”运算符重载,比较两个类里面的成员是否相等,返回值为bool类型 16 bool operator==(Person& p1, Person& p2) 17 { 18 if (p1.age == p2.age && p1.name == p2.name) 19 { 20 return true; 21 } 22 else 23 { 24 return false; 25 } 26 } 27 //函数模板 28 template<class T> 29 //利用函数模板创建的函数 30 bool myCompare(T& a, T& b) 31 { 32 if (a == b) 33 { 34 return true; 35 } 36 else 37 { 38 return false; 39 } 40 } 41 42 43 44 void test01() 45 { 46 int a = 10; 47 int b = 20; 48 bool ret1 = myCompare(a, b); 49 if (ret1) 50 { 51 cout << "a和b相等" << endl; 52 } 53 else 54 { 55 cout << "a和b不相等" << endl; 56 } 57 } 58 //比较类成员是否相等 59 void test02() 60 { 61 //创建两个类P1和P2 62 Person p1(10, "tom"); 63 Person p2(10, "tom"); 64 65 bool ret2 = myCompare(p1, p2); 66 if (ret2) 67 { 68 cout << "p1 is p2" << endl; 69 } 70 else 71 { 72 cout << "p1 is not p2" << endl; 73 } 74 } 75 int main() 76 { 77 test01(); 78 test02(); 79 system("pause"); 80 return 0;
//方法二:利用具体 化的Person版本实现代码,具体化优先调用 81 }
posted @ 2021-07-22 16:56  卿源  阅读(105)  评论(0)    收藏  举报