2023.4.21
1 #include <iostream> 2 using namespace std; 3 //通过成员函数重载+号 4 class Person 5 { 6 public: 7 Person operator+(Person &p) 8 { 9 Person temp; 10 temp.m_A = this->m_A + p.m_A; 11 temp.m_B = this->m_B + p.m_B
12 return p; 13 } 14 public: 15 int m_A; 16 int m_B; 17 }; 18 int main() 19 { 20 Person p1; 21 Person p2; 22 Person p3; 23 p1.m_A = 10; 24 p1.m_B = 20; 25 p2.m_A = 30; 26 p2.m_B = 40; 27 p3 = p1 + p2; 28 cout<<p3.m_A<<endl; 29 cout<<p3.m_B<<endl; 30 return 0; 31 }
1 #include <iostream> 2 using namespace std; 3 //通过全局函数重载+号 4 class Person 5 { 6 public: 7 int m_A; 8 int m_B; 9 }; 10 Person operator+(Person &p1,Person &p2) 11 { 12 Person temp; 13 temp.m_A = p1.m_A + p2.m_A; 14 temp.m_B = p1.m_B + p2.m_B; 15 return temp; 16 } 17 int main() 18 { 19 Person p1; 20 Person p2; 21 Person p3; 22 p1.m_A = 10; 23 p1.m_B = 20; 24 p2.m_A = 30; 25 p2.m_B = 40; 26 p3 = p1 + p2; 27 cout<<p3.m_A<<endl; 28 cout<<p3.m_B<<endl; 29 return 0; 30 }
1 #include <iostream> 2 using namespace std; 3 //只能利用全局函数重载左翼运算符 4 class Person 5 { 6 public: 7 int m_A; 8 int m_B; 9 }; 10 ostream &operator<<(ostream &cout,Person &p) 11 { 12 cout<<"m_A = "<<p.m_A<<"m_B = "<<p.m_B; 13 return cout; 14 } 15 void test01() 16 { 17 Person p; 18 p.m_A = 10; 19 p.m_B = 20; 20 cout << p << endl; 21 } 22 int main() 23 { 24 test01(); 25 return 0; 26 }