1 #include <iostream> // 标准的输入输出
2 using namespace std;
3
4 class Person {
5 public:
6 Person() {}
7 Person(int a, int b)
8 ¦ : m_A(a)
9 ¦ , m_B(b)
10 {
11 }
12
13 // 利用成员函数重载加法运算符
14 /* Person operator+(Person& p)
15 {
16 ¦ Person p3;
17 ¦ p3.m_A = this->m_A + p.m_A;
18 ¦ p3.m_B = this->m_B + p.m_B;
19 ¦ return p3;
20 }*/
21 int m_A;
22 int m_B;
23 };
24
25 // 全局函数重载加号运算符
26 Person operator+(Person& p1, Person& p2)
27 {
28 Person p3;
29 p3.m_A = p1.m_A + p2.m_A;
30 p3.m_B = p1.m_A + p2.m_B;
31 return p3;
32 }
33
34 void test01()
35 {
36 Person p1(10, 10);
37 Person p2(20, 20);
38 Person p3;
39 p3 = p1 + p2;
40 cout << p3.m_A << "___" << p3.m_B << endl;
41 }
42
43 int main()
44 {
45 test01();
46 return 0;
47 }
C++ 加号运算符重载
最新推荐文章于 2024-04-30 00:14:40 发布