c++运算符加号重载

运算符重载
对已有的运算符重新进行定义,赋予另一种功能,以适应不同的数据类型


加号运算符重载
实现两个自定义数据类型相加运算

operator+()函数游戏用提供

 

可以通过成员函数重载实现和全局函数重载实现

 

 

 

 1 #include<iostream>
 2 using namespace std;
 3 
 4 
 5 class Persion
 6 {
 7 public:
 8     Persion() {}
 9     Persion(const Persion& p)//拷贝构造函数
10     {
11         this->m_A = p.m_A;
12         this->m_B = p.m_B;
13     }
14     Persion(int a, int b)
15     {
16         m_A = a;
17         m_B = b;
18     }
19     Persion operator+(int a)//运算符重载函数重载
20     {
21         Persion tem;
22         tem.m_A = this->m_A + a;
23         return tem;
24         
25     }
26     Persion operator+(Persion& p)//成员函数重载实现运算符加号重载
27     {
28         Persion tem;
29         tem.m_A = this->m_A + p.m_A;
30         tem.m_B = this->m_B + p.m_B;
31         return tem;
32     }
33     int m_A;
34     int m_B;
35 };
36 //Persion operator+(Persion& p, Persion& q)//全局函数实现加号运算符重载
37 //{
38 //    Persion tem;
39 //    tem.m_A = p.m_A + q.m_A;
40 //    tem.m_B = p.m_B + q.m_B;
41 //    return tem;
42 //}
43 
44 int main()
45 {
46     Persion p1(10, 10);
47     Persion p2(p1);//调用Persion(const Persion &p);
48     Persion p3 = p1 + p2;//相当于Persion p3=p1.operator+(p2);
49     Persion p4= p2 + 10;
50     cout << p3.m_A << "," << p3.m_B << endl;
51     return 0;
52 
53 }

 

 

 

 

 运算符重载也可以发生重载

对于内置的数据类型的表达式的运算符不可以改变

不能滥用运算符重载

posted @ 2021-02-17 16:59  两天阿来  阅读(83)  评论(0)    收藏  举报