⚫ C++中的表達式由運算符和操做數按照規則構成。例如,算術運算符包括加「+」、減「-」 、乘「*」 、除「/」和取模「%」。若是不作特殊處理,則這些算術運算符一般只能用於對基本數據類型的常量或變量進行運算,而不能用於對象之間的運算。
⚫ 運算符重載,就是給已有的運算符賦予多重含義,使同一個運算符做用於不一樣類型的數據時產生不一樣的行爲。運算符重載的目的是使得C++中的運算符也可以用來操做對象。
⚫ 用於類運算的運算符一般都要重載。有兩個運算符,系統提供了默認的重載版本:賦值運算符=和地址運算符&。ios
三、賦值運算符的重載函數
四、淺拷貝和深拷貝this
五、重載流插入運算符和流提取運算符spa
#include<iostream> #include<typeinfo> using namespace std; class Point { private: int x; public: Point(int x1){x=x1;} int get(); Point operator++(); Point operator++(int x); Point operator--(); Point operator--(int x); void operator+(const Point &p); void operator-(const Point &p); Point& operator=(const Point &p); operator double(); friend void operator<<(ostream & stream,Point obj); }; int Point::get(){ return this->x; } //重載運算符(++obj) Point Point::operator++(){ x++; return *this; } //重載運算符(obj++) Point Point::operator++(int x){ Point temp = *this; this->x++; return temp; } //重載運算符(--obj) Point Point::operator--(){ this->x--; return *this; } //重載運算符(obj--) Point Point::operator--(int x){ Point temp = *this; this->x--; return temp; } //重載運算符+(a+b) void Point::operator+(const Point &p){ this->x=this->x+p.x; } //重載運算符-(a-b) void Point::operator-(const Point &p){ this->x=this->x-p.x; } //複製運算符重載=(a=b),賦值運算符必須重載爲成員函數 Point& Point::operator=(const Point &p){ this->x=p.x; return *this; } //重載類型轉換運算符()a Point::operator double(){ cout << "重載類型轉換運算符" << endl; return this->x; } //重載運算符 (cout <<) void operator<<(ostream & stream,Point obj){ stream<< obj.x <<endl; } int main(){ Point point(10); operator<<(cout, point.operator++());//11 Point point2(10); operator<<(cout, point2.operator++(0));//10 Point point3(10); operator<<(cout, point3.operator--());//9 Point point4(10); operator<<(cout, point4.operator--(0));//10 Point point5(1); Point point6(1); point5.operator+(point6); operator<<(cout, point5);//2 point5.operator-(point6); operator<<(cout, point5);//1 Point point7(1); Point point8(5); operator<<(cout, point7.operator=(point8));//5 Point point9(20); cout << typeid(point9.get()).name()<< endl;//i cout << point9.operator double()<< endl; cout << typeid(point9.operator double()).name();//d return 0; }