C++ //运算符重载 +号

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 
 5 //1.成员函数重载 +号
 6 class Person
 7 {
 8 public:
 9 
10     //Person operator+(Person& p)
11     //{
12     //    Person temp;
13     //    temp.m_A = this->m_A + p.m_A;
14     //    temp.m_B = this->m_B + p.m_B;
15     //    return temp;
16     //}
17     int m_A;
18     int m_B;
19 };
20 
21 //2.全局函数重载 +号
22 Person operator+(Person& p1, Person& p2)
23 {
24     Person temp;
25     temp.m_A = p1.m_A + p2.m_A;
26     temp.m_B = p1.m_B + p2.m_B;
27 
28     return temp;
29 }
30 //函数重载
31 Person operator+(Person& p1, int num)
32 {
33     Person temp;
34     temp.m_A = p1.m_A + num;
35     temp.m_B = p1.m_B + num;
36 
37     return temp;
38 
39 }
40 
41 void test01()
42 {
43     Person p1;
44 
45     p1.m_A = 10;
46     p1.m_B = 20;
47 
48     Person p2;
49 
50     p2.m_A = 10;
51     p2.m_B = 20;
52     //成员函数重载本质调用
53     //Person p3 = p1.operator+(p2);
54     //成员简化
55     //Person p3 = p1 + p2;
56 
57     //全局函数.
58 
59     Person p3 = operator+(p1, p2);
60     //全局函数简化
61     //Person p3 = p1 + p2;
62 
63     //运算符重载也可以发生函数重载
64     Person p4 = p1 + 100;   //Person  +int
65 
66     cout << "p3 .m_A = " << p3.m_A << endl;
67 
68     cout << "p3 .m_B = " << p3.m_B << endl;
69 
70 
71     cout << "p4 .m_A = " << p4.m_A << endl;
72     cout << "p4 .m_B = " << p4.m_B << endl;
73 
74 }
75 
76 
77 int main()
78 {
79     test01();
80 }

 

posted on 2021-08-07 14:33  Bytezero!  阅读(115)  评论(0编辑  收藏  举报