标签:构造 name ace iostream col tor cout 函数重载 bsp
作用:实现两个自定义数据类型的加法运算
1 #include <iostream> 2 using namespace std; 3 4 class Person 5 { 6 public: 7 8 //1.成员函数重载加号运算符 9 /*Person operator+(Person &p) 10 { 11 Person temp; 12 temp.m_A = this->m_A + p.m_A; 13 temp.m_B = this->m_B + p.m_B; 14 return temp; 15 }*/ 16 17 int m_A; 18 int m_B; 19 20 }; 21 22 //2.全局函数重载加号运算符 23 Person operator+(Person &p1,Person &p2) 24 { 25 Person temp; 26 temp.m_A = p1.m_A + p2.m_A; 27 temp.m_B = p1.m_B + p2.m_B; 28 return temp; 29 } 30 31 //函数重载的版本 32 Person operator+(Person &p1, int num) 33 { 34 Person temp; 35 temp.m_A = p1.m_A + num; 36 temp.m_B = p1.m_B + num; 37 return temp; 38 } 39 41 void test_01(void) 42 { 43 Person p1; 44 p1.m_A = 11; 45 p1.m_B = 11; 46 47 Person p2; 48 p2.m_A = 10; 49 p2.m_B = 10; 50 51 //成员函数重载本质调用 52 //Person p3 = p1.operator+(p2); 53 54 //全局函数重载本质调用 55 //Person p3 = operator+(p1, p2); 56 57 Person p3 = p1 + p2;//从这里开始构造加号运算符重载函数,返回值为对象,传入一个引用对象就可以了 58 59 //运算符重载,也可以发生函数重载 60 Person p4 = p1 + 100; 61 62 63 cout << p3.m_A << endl; 64 cout << p3.m_B << endl; 65 66 cout << p4.m_A << endl; 67 cout << p4.m_B << endl; 68 } 69 70 int main(void) 71 { 72 test_01(); 73 74 system("pause"); 75 return 0; 76 }
标签:构造 name ace iostream col tor cout 函数重载 bsp
原文地址:https://www.cnblogs.com/huanian/p/12763317.html