プログラミング言語 C++ における演算子オーバーロードの糖衣構文的な解釈と、フレンド関数による解決
1. 演算子オーバーロードの糖衣構文的な解釈
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
#include <iostream> using namespace std; class coord { int x, y; public: coord() : x(0), y(0) {} coord(int i, int j) : x(i), y(j) {} void show() { cout << "x = " << x << ", y = " << y << endl; } coord operator+(coord position); coord add(coord position); }; coord coord::operator+(coord position) { coord temp; temp.x = this->x + position.x; temp.y = this->y + position.y; return temp; } coord coord::add(coord position) { coord temp; temp.x = this->x + position.x; temp.y = this->y + position.y; return temp; } int main() { coord position_a(10, 10), position_b(5, 3); coord position_m = position_a + position_b; position_m.show(); // => x = 15, y = 13 coord position_n = position_a.add(position_b); position_n.show(); // => x = 15, y = 13 return 0; } |
※ 説明をシンプルにするために参照渡しやconst修飾は省略しています。

