# C++的操作符重載概述

1.什麼是操作符重載

C++中的操作符很多，如+，-，*，\等等。

C++中的重載也是C++中物件導向多態的體現。

C++中有：int a=2+3;　　那麼a=5

#include <iostream>using namespace std;    class Point{public:    int x;    int y;    Point(int _x,int _y):x(_x),y(_y){    }        Point operator+(Point &p){        int t1=this->x+p.x;        int t2=this->y+p.y;        Point t(t1,t2);        return t;    }};    int main(){    Point p1(1,3);    Point p2(2,6);    Point p3 = p1+p2;    cout<<"p3:("<<p3.x<<","<<p3.y<<")";     ///執行輸出：p3:(3,9)    return 0;}

2.操作符重載的方式

class Point{public:    int x;    int y;    Point(int _x,int _y);        Point operator+(Point &p);  ///類成員函數，類成員函數可以使用this指標擷取自身對象        friend int operator*(Point &p1,Point &p2);  ///友元函數};

3.操作符重載例子

#include <iostream>using namespace std;    class Point{public:    int x;    int y;    Point(int _x,int _y):x(_x),y(_y){    }        Point operator+(Point &p){  ///實現座標向量加        int t1=this->x+p.x;        int t2=this->y+p.y;        Point t(t1,t2);        return t;    }        friend int operator*(Point &p1,Point &p2);  ///實現內積};    int operator*(Point &p1,Point &p2){    return (p1.x*p2.x)+(p1.y*p2.y);}    int main(){    Point p1(1,3);    Point p2(2,6);    cout<<p1*p2<<endl;  ///輸出內積：20        Point p3 = p1+p2;    cout<<"p3:("<<p3.x<<","<<p3.y<<")"<<endl;   ///輸出座標和：(3,9)    return 0;}

## E-Commerce Solutions

Leverage the same tools powering the Alibaba Ecosystem

## Apsara Conference 2019

The Rise of Data Intelligence, September 25th - 27th, Hangzhou, China

## Alibaba Cloud Free Trial

Learn and experience the power of Alibaba Cloud with a free trial worth \$300-1200 USD