質問するログイン新規登録

回答編集履歴

2

コードを追加しました。

2020/02/21 07:51

投稿

ameagari_hare
ameagari_hare

スコア39

answer CHANGED
@@ -28,4 +28,5 @@
28
28
  for (int i = 0; i < 4; ++i) {
29
29
  std::cout << "operator " << ops_str[i] << ": " << half << " " << ops_str[i] << " " << sixth << " = " << ops[i]( half, sixth ) << "\n";
30
30
  }
31
+ }
31
- }```
32
+ ```

1

コードを追加しました。

2020/02/21 07:51

投稿

ameagari_hare
ameagari_hare

スコア39

answer CHANGED
@@ -2,4 +2,30 @@
2
2
 
3
3
  friend関数を前方宣言すれば良いようです。
4
4
  https://wandbox.org/permlink/ARajJldEjsVlk1kA
5
+ ```C++
6
+ class Fraction;
7
+ Fraction operator+( Fraction, Fraction );
8
+ Fraction operator-( Fraction, Fraction );
9
+ Fraction operator*( Fraction, Fraction );
10
+ Fraction operator/( Fraction, Fraction );
11
+
12
+ class Fraction {
13
+ ...
14
+ };
15
+
16
+ int main() {
17
+ Fraction half(5, 10);
5
- デバッグ目的のようなので、十分かと思います。
18
+ Fraction sixth(6, 36);
19
+
20
+ std::cout << "operator +: " << half << " + " << sixth << " = " << half + sixth << "\n";
21
+ std::cout << "operator -: " << half << " - " << sixth << " = " << half - sixth << "\n";
22
+ std::cout << "operator *: " << half << " * " << sixth << " = " << half * sixth << "\n";
23
+ std::cout << "operator /: " << half << " / " << sixth << " = " << half / sixth << "\n";
24
+
25
+ // 以下の正しいやり方が知りたい
26
+ std::vector<std::string> ops_str{"+", "-", "*", "/"};
27
+ std::vector ops{&operator+, &operator-, &operator*, &operator/};
28
+ for (int i = 0; i < 4; ++i) {
29
+ std::cout << "operator " << ops_str[i] << ": " << half << " " << ops_str[i] << " " << sixth << " = " << ops[i]( half, sixth ) << "\n";
30
+ }
31
+ }```