宿題
operator<<、operator==、operator!= の両方をオーバーロードする必要があります。
.h ファイルと .cpp ファイルは以下に含まれています。
namespace JoePitz
{
class Complex
{
// declare friend functions
friend ostream &operator<<(ostream &out, const Complex &value);
friend ostream &operator<<(ostream &out, const bool &value);
friend istream &operator>>(istream &in, Complex &value);
public:
// constructor
Complex(double real, double imaginary);
// overloading +/-/==/!= operators
Complex operator+(const Complex &compx2);
Complex operator-(const Complex &compx2);
bool operator==(const Complex &compx2);
bool operator!=(const Complex &compx2);
private:
double real;
double imaginary;
void initialize(double real, double imaginary);
};
// GCC requires friend functions to be declared in name space
ostream &operator<<(ostream &out, const Complex &value);
ostream &operator<<(ostream &out, const bool &value);
istream &operator>>(istream &in, Complex &value);
}
excerpt from .cpp file
ostream& JoePitz::operator<<(ostream &out, const Complex &value)
{
// print real
cout << value.real;
// print imaginary
if (value.imaginary == ISZERO)
{
cout << POSSIGN << value.imaginary << IMAGNSGN;
}
else if (value.imaginary > ISZERO)
{
cout << POSSIGN << value.imaginary << IMAGNSGN;
}
else
{
cout << value.imaginary << IMAGNSGN;
}
return out;
}
ostream& JoePitz::operator<<(ostream &out, const bool &value)
{
return out;
}
// overloaded == operator
bool JoePitz::Complex::operator==(const Complex &compx2)
{
return (this->real == compx2.real && this->imaginary == compx2.imaginary);
}
// overloaded != operator
bool JoePitz::Complex::operator!=(const Complex &compx2)
{
return !(this->real == compx2.real && this->imaginary == compx2.imaginary);
}
次のコンパイル エラーを受け取りました。
../src/hw4.cpp:71: エラー: 'c1 << " * * *\012"' の 'operator<<' に一致しません ../src/Complex.h:54: 注: 候補は: std::ostream& JoePitz::operator<<(std::ostream&, const bool&) ../src/Complex.h:53: 注意: std::ostream& JoePitz::operator<<(std::ostream&, const JoePitz ::複雑&)
私の理解では、これは実装するオーバーロードされた関数がわからないことによるものです。
私が抱えている問題は、operator<< 関数が ostream を返し、Complex オブジェクトを受け入れるという事実に対処する方法ですが、operator== 関数は bool を返します。
しかし、bool または Complex オブジェクトを処理するように operator== 関数を変更する方法がわかりません。bool を返す別のオーバーロードされた opperator<< 関数を追加しようとしましたが、コンパイラにはまだ問題があります。
どんな援助でも大歓迎です。