# [C++] 運算子多載

--

`a + b * c`

`add(a, multiply(b, c))`

class coord:

`class coord {    public:    int x, y;    coord(){        x = 0;        y = 0;    }    coord(int a, int b){        x = a;        y = b;    }    coord operator+(const coord &a){        coord tmp;        tmp.x = x + a.x;        tmp.y = y + a.y;        return tmp;    }    coord operator-(const coord &a){        coord tmp;        tmp.x = x - a.x;        tmp.y = y - a.y;        return tmp;    }    coord operator=(const coord &a){        x = a.x;        y = a.y;        return *this;    }};`

main:

`int main() {    coord c0(1,1), c1(2,2), c2(3,3), c3, c4;    c3 = c0 + c1 + c2;    c4 = c0 - c1 - c2;    std::cout << c3.x << " " << c3.y << "\n";    std::cout << c4.x << " " << c4.y << "\n";    return 0;}`

output:

`6 6-4 -4`

`class coord {    public:    int x, y;    coord(){        x = 0;        y = 0;    }    coord(int a, int b){        x = a;        y = b;    }    friend coord operator+(const coord&, const coord&);    friend coord operator-(const coord&, const coord&);    coord operator=(const coord &a){        x = a.x;        y = a.y;        return *this;    }};coord operator+(const coord &a, const coord &b){    coord tmp;    tmp.x = a.x + b.x;    tmp.y = a.y + b.y;    return tmp;}coord operator-(const coord &a, const coord &b){    coord tmp;    tmp.x = a.x - b.x;    tmp.y = a.y - b.y;    return tmp;}`