C++ の演算子オーバーロード
演算子オーバーロードを使うと、自分の型でも +、==、< などの演算子が使えるようになり(operator+ のような名前の関数で定義します)、<< をオーバーロードすれば std::cout << obj と書けます。
金額をセント単位の整数で持っておけば、小数の丸め誤差に悩まされることはありません。Money クラスを書いたら、2つの金額を足すいちばん自然な書き方は 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+':2つの 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 メンバです。なぜ使えるのでしょうか。private はオブジェクトごとではなくクラスごとに働くからです。Money のメンバ関数は、どの Money の private メンバでも使えます。ステップ実行を押して、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 で、2 回目の += 5 も s に足されます。10 + 5 + 5 = 20。== と !=
2つの分数が等しいのはどんなときでしょうか。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 と表示されます。< と並べ替え
3つ目の引数を渡さないと、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 も、この < を使って順番を決めます。< がなければ、どちらも Song を入れられません。
std::sort(v.begin(), v.end()); には 3 つ目の引数がありません。要素の順番を決めるのに、どの演算子を使いますか?
std::sort はふつう < を使います。a < b が真なら a が b の前に来ます。だから自分の型に operator< を書けば、そのまま並べ替えられます。時刻を順番に
✓Time に operator< を書きましょう。時が早いほうが先で、時が同じなら分で比べます。そうすれば std::sort が3つ目の引数なしで使えます。
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 と書けたら便利でしょう。ただし << の左側は Money ではなく std::cout なので、Money のメンバ関数にはできません。代わりに、左側と右側を2つの引数として受け取る普通の関数として書き、private メンバを使えるように、クラスの中で 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 に << を書いて、分子/分母 の形で表示されるようにしましょう。プログラムは 1人分は 3/4 と表示します。
1人分は 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 << "1人分は " << 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はクラス単位で働きます。メンバ関数は、同じクラスの別のオブジェクトの private メンバも使えます。==と!=は別々に書き、!=は==を使って!(*this == other)と書きます。operator<があれば、std::sortに3つ目の引数はいりません。setやmapでもその型をキーにできます。<<はクラスの外の関数として書き、クラスの中でfriendと宣言します。std::ostream&を返すので、<<を続けて書けます。- 演算子をオーバーロードするのは、意味が明らかなときだけにしましょう。迷ったら、わかりやすい名前のメンバ関数を書きます。