前提
C++のオブジェクト指向で複素数の計算を実装してみました。
実現したいこと
もし、入力された二つの複素数が同じ、片方が大きいまたは小さい場合、trueかfalseで結果を返したい。
0か1でreturnするのではなく、true,falseで返したい。
方法が見つからなかったのと、自分で実装するのにも上手くいかなかったのでアドバイスと指摘をいただけたらと思います。
該当のソースコード
C++#include
1using namespace std; 2 3class Complex{ 4 public: 5 const bool operator==(const Complex&) const; 6 const bool operator!=(const Complex&) const; 7 const bool operator>(const Complex &n) const; 8 const bool operator<(const Complex &n) const; 9 friend ostream &operator<<( ostream& out, const Complex &n); 10 friend istream &operator>>( istream& in, Complex &n); 11 Complex(){ 12 this->real = 0; 13 this->imaginary = 0; 14 } 15 Complex(int r, int i){ 16 this->real = r; 17 this->imaginary = i; 18 } 19 private: 20 int real; 21 int imaginary; 22}; 23 24const bool Complex::operator==(const Complex &n) const 25{ 26 if((real == n.real) && (imaginary == n.imaginary)) 27 return true; 28 else 29 return false; 30} 31const bool Complex::operator>(const Complex &n) const 32{ 33 if((real>n.real) || (real==n.real&&imaginary > n.imaginary)) 34 return true; 35 else 36 return false; 37} 38const bool Complex::operator<(const Complex &n) const 39{ 40 if((real<n.real) || (real==n.real&&imaginary < n.imaginary)) 41 return true; 42 else 43 return false; 44} 45 46 47ostream &operator<<( ostream& out, const Complex &n){ 48 if(n.imaginary<0){ 49 out << n.real << n.imaginary << "i"; 50 return out; 51 }else{ 52 out << n.real << "+" << n.imaginary << "i"; 53 return out; 54 } 55} 56istream &operator>>( istream& in, Complex &n){ 57 in >> n.real >> n.imaginary; 58 return in; 59} 60int main(){ 61 62 Complex C1; 63 Complex C2; 64 for(int i=0;i<2;++i){ 65 cin >> C1 ; 66 cin >> C2 ; 67 bool varBool = C1 == C2; 68 bool varBool2 = C1 > C2; 69 bool varBool3 = C1 < C2; 70 cout<<"C1==C2? "<<varBool<<endl; 71 cout<<"C1>C2? "<<varBool2<<endl; 72 cout<<"C1<C2? "<<varBool3<<endl; 73 74 cout<<"=============="<<endl; 75 76 } 77 return 0; 78} 79 80 81 82 83 84
試したこと
どうしてもtrue、falseを文字列で表示したくて直接””を記入した。
return "false"
return "true"
当たり前だが、真の場合は1,偽は0としか表示されない。
これ?
https://mickey24.hatenablog.com/entry/20110111/1294745520

回答2件
あなたの回答
tips
プレビュー