大幅に書き変えました, すみません.
演算子の練習をしているのですが, 以下のエラーがでてしまいます.
どこを直せば良いですか?
11th.operator.cpp:32:23: error: assigning to 'double' from incompatible type 'A' a3.x = (*this)*s; ~~~~~~~^~ 11th.operator.cpp:45:19: error: member reference base type 'double' is not a structure or union x += a.x;
c++
1#include <iostream> 2 3using namespace std; 4 5class A{ 6 double x; 7public: 8 A operator+(A a) // やりたいこと: (*this) + a; 9 { 10 A a1; 11 a1.x = (*this).x + a.x; 12 return a1; 13 } 14 A operator-(A a) // やりたいこと: (*this) - a; 15 { 16 A a2; 17 a2.x = (*this).x - a.x; 18 return a2; 19 } 20 bool operator>(A a) // やりたいこと: (*this) > a; 21 { 22 return (*this).x > a.x; 23 } 24 bool operator==(A a){ // やりたいこと: (*this) == a; 25 return (*this).x == a.x; 26 } 27 A operator*(double s) // やりたいこと: (*this)*s; 28 { 29 A a3; 30 a3.x = (*this)*s; 31 return a3; 32 } 33 double& operator[](int i){ // やりたいこと: (*this).x = some thing; 34 return (*this).x; 35 } 36 37 A &operator=(const A &a){ // やりたいこと: (*this) = a; 38 (*this).x = a.x; 39 return (*this); 40 } 41 A& operator<<(double a){ // やりたいこと: (*this) << a; 42 43 x += a.x; 44 return (*this); 45 } 46 47}; 48// 以下に正しい出力を示しておく. 49// 1, 2 50// 1 < 2 51// 1 != 2 52// 3, 2 53// 1, 2 54// 2, 2 55// 4 56// 8 57// 10 58// 16 59 60int main(){ 61 A a1, a2; 62 63 a1[0] = 1; 64 a2[-1] = 2; 65 66 cout << a1[-9999] << ", " << a2[0] << "\n"; 67 68 if(a1 > a2){ 69 cout << a1[1651651] << " > " << a2[0] << "\n"; 70 }else{ 71 cout << a1[0] << " < " << a2[0] << "\n"; 72 } 73 74 if(a1 == a2){ 75 cout << a1[0] << " == " << a2[0] << "\n"; 76 }else{ 77 cout << a1[0] << " != " << a2[0] << "\n"; 78 } 79 80 a1 = a1 + a2; 81 cout << a1[0] << ", " << a2[0] << "\n"; 82 83 a1 = a1 - a2; 84 cout << a1[0] << ", " << a2[0] << "\n"; 85 86 a1 = a2; 87 cout << a1[0] << ", " << a2[0] << "\n"; 88 89 a1 = a1*2; 90 cout << a1[0] << "\n"; 91 a1 = a1 + a2*2; 92 cout << a1[0] << "\n"; 93 94 a1 << 2; 95 cout << a1[0] << "\n"; 96 97 a1 << 1 << 2 << 3; 98 cout << a1[0] << "\n"; 99 100 101 return 0; 102}
回答1件
あなたの回答
tips
プレビュー