运算符重载概念:对已有的运算符重新进行定义,赋予其另一种功能,以适应不同的数据类型
4.5.1 加法运算符重载
作用:实现两个自定义数据类型相加的运算
- 成员函数重载+号
- 全局函数重载+号 ```cpp class Person{ public:
//1. 成员函数重载+号 person operator+ (person &p) { person temp; temp.m_a = this -> m_a + p.m_a; temp.m_b = this -> m_b + p.m_b; return temp;
}int m_a;int m_b;
};
//2. 全局函数重载+号 person operator+ (person & p1 , person & p2) { person temp; temp.m_a = p1.m_a+p2.m_a; temp.m_b = p1.m_b+p2.m_b; return temp; }
void test01() { person p1; p1.m_a = 10; p2.m_b = 10;
person p1;p1.m_a = 10;p2.m_b = 10;//成员函数重载本质调用//person p3 = p1.operator + (p2);//person p3 = operator+(p1, p2);person p3 = p1 + p2;
}
<a name="RnJy8"></a>####<a name="vX5oN"></a>#### 4.5.2 左移运算符重载作用:可以输出自定义数据类型<br />```cpp#include <ostream>class person{friend ostream & operator<<(ostream &cout , person & p);private://利用成员函数 左移运算符//void operator <<(person &p) //不是想要的结果p.operator(cout)//void operator <<(cout) //无法实现cout在左侧//以上两个原因,所以一般左移运算符不用成员函数实现int m_a;int m_b;public:person(int a, int b){m_a = a;m_b = b;}};//只能利用全局函数重载左移运算符//返回ostream是为了链式编程(详见函数调用),不然就只能到cout << p;ostream & operator<<(ostream &cout , person & p){cout << "m_a = " << p.m_a << ", m_b = " << p.m_b << endl;return cout;}void test01(){person p(10, 10);cout << p << endl;}
4.5.3 递增运算符
作用:通过重载递增运算符,实现自己的整形数据
class myintegaer{public:myinterger(){m_num = 0;}//前置++myinterger& operator++(){//先++m_num++;//在返回reutrn *this;}//后置++//int做占位符int,不加占位符,编译器无法区分两个递增。因为返回值不做为成员函数区分myinterger operator++(int){//先“返回”myinterger temp = *this;n_num++;return temp;}private:int m_num;};void test01(){myinterger myint;cout << myint++ << endl;cout << myint << endl;}void test02(){myinterger myint;cout << ++myint << endl;cout << myint << endl;}
4.5.4 赋值运算符重载(未看)
c++编译器至少给一个类添加4个函数
- 默认构造函数(无参,函数体为空)
- 默认析构函数(无参,函数体为空)
- 默认拷贝构造函数,对属性进行值拷贝
- 赋值运算符operator=,对属性进行值拷贝
