1.加号运算符重载,这里用编译器统一的名称operator代替函数名
#include<iostream> using namespace std; //1.成员函数的加号重载 //2.全局函数的加号重载 class Person { public:Person() {};//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;//}Person(int a ,int b){this->m_A = a;this->m_B = b;}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 p3;Person p1(10,10);Person p2(10,10);//1.成员函数加号重载实质//p3=p1.operator+(p2);//cout << p3.m_A << " " << p3.m_B << endl;//当实现了加号重载,就可以简化写成这样//2.全局函数加号重载实质p3 = operator+(p1, p2);cout << p3.m_A << " " << p3.m_B << endl;p3 = p1 + p2;cout << p3.m_A << " " << p3.m_B << endl; } int main() {test01(); }
2.左移运算符重载
1.成员函数重载(行不通),会导致p在左,cout在右的问题
//全局函数左移重载
//这里cout的函数类型是ostream,这里cout前加引用是为了保证cout的唯一,引用即给cout起别名的意思
//为了能够连续cout<<...<<...<<...返回值必须是cout#include<iostream> using namespace std;class Person {friend ostream& operator<<(ostream& cout, Person& p); public:Person(int a, int b){this->m_A = a;this->m_B = b;} private:int m_A;int m_B; };//全局函数左移重载 //这里cout的函数类型是ostream,这里cout前加引用是为了保证cout的唯一,引用即给cout起别名的意思 //为了能够连续cout<<...<<...<<...返回值必须是cout ostream& operator<<(ostream& cout, Person& p) {cout << "m_A = " << p.m_A << " " << "m_B = " << p.m_B;return cout; }void test01() { Person p(10, 10);//由于p是自定义类型的变量,cout并不知道返回什么,因此要自己实现cout函数的返回cout << p << endl; } int main() {test01(); }
在观看视频,敲代码的时候,我思考为什么Person &一个函数,于是我搜了以下解释:
3.递增运算符重载
#include<iostream> using namespace std;class MyInteger {friend ostream& operator<<(ostream& cout, MyInteger myint); public:MyInteger(){m_Num = 0;}//1.前置++ 这里用引用是为了一直为一个数据进行递增操作//例如++(++myint)时,里面myint从1变为了2,导致更换了数据.//其实本质就是不用引用返回,每次返回的就是一个新对象,拷贝调用原则//防止拷贝构造函数,新的对象会调用新的拷贝构造函数//这里面的this指针是全局变量!!!!MyInteger &operator++(){this->m_Num++;return *this;}//2.后置++ 这里的是占位参数,用来区分前置++与后置++的//如果这里用引用的话&operator++,这里会返回局部变量的引用,该函数调用完后temp被释放,后面再解引用后会造成非法操作了MyInteger operator++(int){ //先 记录当前的结果MyInteger temp = *this;//后递增m_Num++;return temp;}private:int m_Num; };void test01() { MyInteger myint;//cout << ++(++myint) << endl;cout << ++myint << endl; }void test02() {MyInteger myint;cout << myint++ << endl;cout << myint << endl; } ostream& operator<<(ostream& cout, MyInteger myint) {cout << "m_Num的值为: " << myint.m_Num;return cout; }int main() {/*test01();*/test02(); }