C++运算符重载

1、"+"运算符重载:

 1 #include<iostream>
 2 using namespace std;
 3 class Person
 4 {
 5 public:
 6     int m_A;
 7     int m_B;
 8     //成员函数运算符重载
 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 //相当于Person P3=P1.operator+(P2);
18 
19 //全局函数运算符重载
20 Person operator+(Person& P1, Person& P2)
21 {
22     Person temp;
23     temp.m_A = P1.m_A + P2.m_A;
24     temp.m_B = P1.m_B + P2.m_B;
25     return temp;
26 }
27 //相当于Person P3=operator+(P1+P2);or   Person P3=P1+P2;

2、"-"运算符重载同比“+”运算符一样,较容易得出;

3、“<<”(左移运算符)重载:

 1 //1.链式编程思想
 2 cout << m1 << m2 << m3 << m4;//返回数值都是cout的数据类型
 3 
 4 //2.左移运算符不能用成员函数只能用全局函数
 5 
 6 //ostream是<<的数据类型
 7 ostream& operator<<(ostream& cout, Person& p)
 8 {
 9     cout << "m_A" << P.m_A << "m_B" << p.m_B;
10     return cout;//返回的是cout的数据类型
11 }

4.递增运算符重载:

 1 //前置“++”运算符重载
 2 myInteger& operator++()
 3 {
 4     m_num++;
 5     return *this;
 6 }
 7 //后置“++”运算符重载
 8 myInteger operator++(int)//int表示占位参数,可以区分前置和后置递增
 9 {
10     myinteger temp = *this;
11     m_num++;
12     return temp;
13 }
14 //后置递增myInteger后不用加&(引用值)

附加知识点:通过一个类型加上一个()会创建一个匿名对象,匿名对象用完立即被释放。

posted @ 2021-07-22 17:26  卿源  阅读(94)  评论(0)    收藏  举报