[C++] 運算子多載
3 min readSep 23, 2021
--
在程式設計中,運算子多載(英語:operator overloading)是多型的一種。這裡,運算子(比如+,=或==)被當作多型函式,它們的行為隨著其參數類型的不同而不同。運算子並不一定總是符號。
運算子多載通常只是一種語法糖。它可以簡單地通過函式呼叫來類比:
a + b * c
在一個支援運算子多載的語言裡,上面的寫法要比下面的寫法有效而簡練:
add(a, multiply(b, c))
**可定義的運算子: https://docs.microsoft.com/zh-tw/cpp/cpp/operator-overloading?view=msvc-160
假設我們要設計一個座標的class,須具備座標相加、相減跟賦值的功能。其功能需用運算子的方式來實現。
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
除了在類別中做運算子過載,也可以在類別外用函式實作,注意函式實作式兩個arguments,以及得用friend來讓函式可以存取coord的資料。
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;
}