This commit is contained in:
Jidong Xiao
2025-02-20 23:00:55 -05:00
committed by JamesFlare
parent f95296f4d1
commit 3da5d38338
6 changed files with 353 additions and 0 deletions

View File

@@ -0,0 +1,39 @@
#include <cmath>
#include "complex.h"
// Assignment operator
Complex& Complex::operator= (Complex const& rhs) {
real_ = rhs.real_;
imag_ = rhs.imag_;
return *this;
}
// Addition operator as a member function.
Complex Complex::operator+ (Complex const& rhs) const {
double re = real_ + rhs.real_;
double im = imag_ + rhs.imag_;
return Complex(re, im);
}
// Subtraction operator as a non-member function.
Complex operator- (Complex const& lhs, Complex const& rhs) {
return Complex(lhs.Real()-rhs.Real(), lhs.Imaginary()-rhs.Imaginary());
}
// Unary negation operator. Note that there are no arguments.
Complex Complex::operator- () const {
return Complex(-real_, -imag_);
}
// Input stream operator as a friend function
istream& operator>> (istream & istr, Complex & c) {
istr >> c.real_ >> c.imag_;
return istr;
}
// Output stream operator as an ordinary non-member function
ostream& operator<< (ostream & ostr, Complex const& c) {
if (c.Imaginary() < 0) ostr << c.Real() << " - " << -c.Imaginary() << " i ";
else ostr << c.Real() << " + " << c.Imaginary() << " i ";
return ostr;
}