C++ 運算子過載
運算子過載讓自己的型別也能用 +、==、< 這些運算子,寫成 operator+ 這樣的函式;過載 << 可以直接 std::cout << 物件。
錢用「分」存成整數,就不會有小數的誤差。寫一個 Money 類,兩筆錢加起來,最自然的寫法是 a + b。可編譯器不知道兩個 Money 怎麼加:
1#include <iostream>2 3class Money {4public:5 Money(int cents) : cents_(cents) {}6 7 int cents() const {8 return cents_;9 }10 11private:12 int cents_;13};14 15int main() {16 Money a{250};17 Money b{199};18 Money total = a + b;19 std::cout << total.cents() << '\n';20 return 0;21}
main.cpp: In function 'int main()':
main.cpp:18:21: error: no match for 'operator+' (operand types are 'Money' and 'Money')
18 | Money total = a + b;
| ~ ^ ~
| | |
| | Money
| Moneyno match for 'operator+':找不到能用在兩個 Money 上的 +。int、double、std::string 的 + 是寫好的;自己的型別,要自己告訴編譯器 + 是什麼意思。這叫運算子過載。
no match for 'operator+' 說的是什麼?
int、double 的 + 是寫好的,自己的型別沒有。要用 +,就自己寫一個 operator+,告訴編譯器怎麼加。過載 +
運算子其實就是一個名字特別的函式:+ 叫 operator+。把它寫成成員函式:
1#include <iostream>2 3class Money {4public:5 Money(int cents) : cents_(cents) {}6 7 Money operator+(const Money& other) const {8 return Money{cents_ + other.cents_};9 }10 11 int cents() const {12 return cents_;13 }14 15private:16 int cents_;17};18 19int main() {20 Money a{250};21 Money b{199};22 Money total = a + b;23 std::cout << total.cents() << '\n';24 return 0;25}
449
a + b 就是 a.operator+(b):左邊的 a 是呼叫它的物件,右邊的 b 是引數 other。+ 不改 a 也不改 b,所以引數是 const 引用,函式本身也加 const,回傳一個新的 Money。
Money① operator+②(const Money& other③) const {④ ...}
- ①返回一筆新的錢
- ②函式名:+ 就叫 operator+
- ③+ 右邊的那個物件
- ④不改 + 左邊的物件
other.cents_ 是 b 的私有成員,為什麼能用?因為 private 是按類算的,不是按物件:Money 的成員函式能用任何一個 Money 的私有成員。點單步,看進入 operator+ 時 other 指向的是 b。
寫好 operator+ 以後,a + b 其實是哪個函式呼叫?
a 是呼叫它的物件,右邊的 b 交給引數 other。修好它:找零
✓程式編譯不過,因為 Money 不會做減法。給它加上 operator-,讓程式顯示 找零:750 分。
找零:750 分
1#include <iostream>2 3class Money {4public:5 Money(int cents) : cents_(cents) {}6 7 int cents() const {8 return cents_;9 }10 11private:12 int cents_;13};14 15int main() {16 Money paid{2000};17 Money price{1250};18 Money change = paid - price;19 std::cout << "找零:" << change.cents() << " 分\n";20 return 0;21}
+= 改自己
+= 和 + 不一樣:它改左邊的物件。所以它不加 const,按習慣返回自己的引用:
1#include <iostream>2 3class Money {4public:5 Money(int cents) : cents_(cents) {}6 7 Money& operator+=(const Money& other) {8 cents_ += other.cents_;9 return *this;10 }11 12 int cents() const {13 return cents_;14 }15 16private:17 int cents_;18};19 20int main() {21 Money wallet{1000};22 wallet += Money{250};23 wallet += Money{75};24 std::cout << wallet.cents() << '\n';25 return 0;26}
1325
*this 就是「這個物件自己」(this 是指向它的指標,第 19 課講指標時再說)。Money{250} 在這裡臨時做出一筆錢,加完就沒了。
a + b一個新的物件加 const,返回新物件a += ba 自己變了不加 const,返回 *this這段程式顯示什麼?
1#include <iostream>2 3class Score {4public:5 Score(int n) : n_(n) {}6 7 Score& operator+=(int k) {8 n_ += k;9 return *this;10 }11 12 int n() const {13 return n_;14 }15 16private:17 int n_;18};19 20int main() {21 Score s{10};22 (s += 5) += 5;23 std::cout << s.n() << '\n';24 return 0;25}
+= 返回的是 s 自己的引用,所以 (s += 5) 的結果還是 s,後面的 += 5 也加在 s 上:10 + 5 + 5 = 20。== 和 !=
兩個分數什麼時候相等?1/2 和 2/4 分子分母都不一樣,可它們是同一個數。== 由你來定:交叉相乘相等,就是相等。!= 照著 == 寫,不用再想一遍:
1#include <iostream>2 3class Fraction {4public:5 Fraction(int num, int den) : num_(num), den_(den) {}6 7 bool operator==(const Fraction& other) const {8 return num_ * other.den_ == other.num_ * den_;9 }10 11 bool operator!=(const Fraction& other) const {12 return !(*this == other);13 }14 15private:16 int num_;17 int den_;18};19 20int main() {21 Fraction half{1, 2};22 Fraction two_quarters{2, 4};23 Fraction third{1, 3};24 std::cout << (half == two_quarters) << '\n';25 std::cout << (half != third) << '\n';26 return 0;27}
1 1
注意 (half == two_quarters) 外面的括號:<< 比 == 先算,不加括號就成了 (std::cout << half) == ...,編譯不過。
注意: 寫了 ==,編譯器不會順手給你 !=(C++20 起才會);< 和 > 也要各寫各的:寫了 <,> 不會自己有。要哪個寫哪個。
!= 照著 == 寫。選一個符號填進空格,讓程式顯示 1。
1#include <iostream>2 3class Point {4public:5 Point(int x, int y) : x_(x), y_(y) {}6 7 bool operator==(const Point& other) const {8 return x_ == other.x_ && y_ == other.y_;9 }10 11 bool operator!=(const Point& other) const {12 return (*this == other);13 }14 15private:16 int x_;17 int y_;18};19 20int main() {21 Point a{1, 2};22 Point b{2, 1};23 std::cout << (a != b) << '\n';24 return 0;25}
!= 就是「不是 ==」:!(*this == other)。(1, 2) 和 (2, 1) 不相等,a != b 是真,顯示 1。< 和排序
std::sort 不給第三個引數時,用的是 <。給自己的型別寫好 operator<,就能直接排序,不用再寫比較函式:
1#include <algorithm>2#include <iostream>3#include <string>4#include <vector>5 6class Song {7public:8 Song(const std::string& title, int seconds) : title_(title), seconds_(seconds) {}9 10 bool operator<(const Song& other) const {11 return seconds_ < other.seconds_;12 }13 14 void show() const {15 std::cout << title_ << " " << seconds_ << " 秒\n";16 }17 18private:19 std::string title_;20 int seconds_;21};22 23int main() {24 std::vector<Song> list{{"清晨", 269}, {"回家的路", 265}, {"夏夜", 226}};25 std::sort(list.begin(), list.end());26 for (const auto& s : list) {27 s.show();28 }29 return 0;30}
夏夜 226 秒 回家的路 265 秒 清晨 269 秒
按時長從短到長排好了。std::set<Song> 和以 Song 為鍵的 std::map 也靠這個 < 排順序,沒有它就放不進去。
std::sort(v.begin(), v.end()); 沒給第三個引數,它用元素的哪個運算子比先後?
std::sort 預設用 <:a < b 為真,a 就排在 b 前面。所以自己的型別只要寫好 operator< 就能直接排。時間排排隊
✓給 Time 寫 operator<:小時早的在前,小時一樣就比分鐘。寫好以後 std::sort 不用第三個引數就能排。
7:45 9:15 9:30
1#include <algorithm>2#include <iostream>3#include <vector>4 5class Time {6public:7 Time(int hours, int minutes) : hours_(hours), minutes_(minutes) {}8 9 void show() const {10 std::cout << hours_ << ":" << minutes_ << '\n';11 }12 13private:14 int hours_;15 int minutes_;16};17 18int main() {19 std::vector<Time> alarms{{9, 30}, {7, 45}, {9, 15}};20 std::sort(alarms.begin(), alarms.end());21 for (const auto& t : alarms) {22 t.show();23 }24 return 0;25}
<< 讓 cout 顯示物件
一直寫 cents() 再自己拼小數點太麻煩,最好能直接 std::cout << price。可 << 的左邊是 std::cout,不是 Money,沒法寫成 Money 的成員函式。辦法是寫成普通函式,兩個引數是左邊和右邊;再在類裡用 friend 宣告它是「朋友」,讓它能用私有成員:
1#include <iostream>2 3class Money {4public:5 Money(int cents) : cents_(cents) {}6 7 friend std::ostream& operator<<(std::ostream& out, const Money& m);8 9private:10 int cents_;11};12 13std::ostream& operator<<(std::ostream& out, const Money& m) {14 out << m.cents_ / 100 << ".";15 if (m.cents_ % 100 < 10) {16 out << "0";17 }18 out << m.cents_ % 100 << " 元";19 return out;20}21 22int main() {23 Money price{1205};24 Money fee{90};25 std::cout << "價格:" << price << '\n';26 std::cout << "運費:" << fee << '\n';27 return 0;28}
價格:12.05 元 運費:0.90 元
std::ostream 是 std::cout 這類輸出流的型別。函式最後返回 out,std::cout << "價格:" << price << '\n' 才能一個接一個地連下去:std::cout << price 的結果還是 std::cout。
std::cout << price << '\n'①;- ①再用返回的 std::cout 接著輸出
這段程式顯示什麼?
1#include <iostream>2 3class Point {4public:5 Point(int x, int y) : x_(x), y_(y) {}6 7 Point operator+(const Point& other) const {8 return Point{x_ + other.x_, y_ + other.y_};9 }10 11 friend std::ostream& operator<<(std::ostream& out, const Point& p);12 13private:14 int x_;15 int y_;16};17 18std::ostream& operator<<(std::ostream& out, const Point& p) {19 out << "(" << p.x_ << ", " << p.y_ << ")";20 return out;21}22 23int main() {24 Point a{1, 2};25 Point b{10, 20};26 std::cout << a + b + a << '\n';27 return 0;28}
a + b 回傳一個新的 Point(11, 22),它再 + a 得到(12, 24)。+ 比 << 先算,所以最後顯示的是加完的結果。顯示一個分數
✓給 Fraction 寫 <<,顯示成 分子/分母。程式要顯示 一份是 3/4。
一份是 3/4
1#include <iostream>2 3class Fraction {4public:5 Fraction(int num, int den) : num_(num), den_(den) {}6 7private:8 int num_;9 int den_;10};11 12int main() {13 Fraction share{3, 4};14 std::cout << "一份是 " << share << '\n';15 return 0;16}
什麼時候值得過載
過載運算子是為了讓程式碼讀起來自然。原則只有一條:讓它做大家一看就猜得到的事。
| 值得 | 別這樣 |
|---|---|
錢、分數、座標的 + - | 用 + 往歌單裡加歌(寫成 add 更清楚) |
能比相等的東西寫 ==(!= 一起寫) | == 只比一部分成員,又不說明 |
有自然先後的東西寫 <,好排序 | 先後不明顯時硬寫 <(換成第 14 課的比較函式) |
想顯示的型別寫 << | << 除了顯示還偷偷改物件 |
拿不準的時候,就寫一個名字清楚的成員函式。
哪一種過載最容易讓人誤會?
playlist + song,沒人能一眼猜到它做什麼,寫成 playlist.add(song) 更清楚。座標相加、分數相等,都是大家一看就懂的意思。這一課學會了
- 運算子是名字特別的函式:
a + b就是a.operator+(b)。自己的型別想用運算子,就自己寫;沒寫時報no match for 'operator+'。 +不改兩邊:引數用const引用、函式加const、回傳一個新物件。+=改自己:不加const,返回*this的引用。private按類算:成員函式能用同一個類的另一個物件的私有成員。==和!=要分別寫,!=照著==寫:!(*this == other)。- 寫好
operator<,std::sort不用第三個引數,set和map也能用它當鍵。 <<寫成類外面的函式,在類裡用friend宣告;它返回std::ostream&,才能連著<<。- 只在意思一看就明白時過載運算子,拿不準就寫一個名字清楚的成員函式。