class Complex
{
public:
// The constructor allows an implicit conversion.
// Watch out for hidden temporaries created by implicit conversions. explicit
Complex(double real, double imaginary = 0) : _real(real), _imaginary(imaginary)
{
}
// 1. Prefer passing objects by const& instead of passing by value.
// 2. "a=a+b" should be rewritten "a+=b".
// operator+ should not modify this object's value, and it should return a temporary object containing the sum
// the return type for the temporary should be "const Complex" (not just "Complex") in order to prevent usage like "a+b=c".
// 3. operator+ should not be a member function.
// you can write "a = b + 1.0" but not "a = 1.0 + b"
// 4. = () [] and -> must be members,
// and class-specific operators new, new[], delete, and delete[] must be static members
void operator+ (Complex other)
{
_real = _real + other._real;
_imaginary = _imaginary + other._imaginary;
}
// operator<< should not be a member function.
// ostream& operator<< (ostream& os, const T& t)
void operator<<(ostream os)
{
os << "(" << _real << "," << _imaginary << ")";
}
Complex operator++() // Complex&
{
++_real;
return *this;
}
Complex operator++(int) // const Complex, prevent a++++
{
Complex temp = *this;
++_real;
return temp;
}
private:
double _real, _imaginary; // real_
};
T& T::operator+= (const T& ohter)
{
//
return *this;
}
const T operator+ (const T& a, const T& b)
{
T temp(a);
temp += b;
return temp;
}
//////////////////////////////////////////////////////////////////////////
class Complex
{
public:
explicit Complex( double real, double imaginary = 0 ) : real_(real), imaginary_(imaginary)
{
}
Complex& operator+=( const Complex& other )
{
real_ += other.real_;
imaginary_ += other.imaginary_;
return *this;
}
Complex& operator++()
{
++real_;
return *this;
}
const Complex operator++( int )
{
Complex temp( *this );
++*this;
return temp;
}
ostream& Print( ostream& os ) const
{
return os << "(" << real_ << "," << imaginary_ << ")";
}
private:
double real_, imaginary_;
};
const Complex operator+( const Complex& lhs, const Complex& rhs )
{
Complex ret( lhs );
ret += rhs;
return ret;
}
ostream& operator<<( ostream& os, const Complex& c )
{
return c.Print(os);
}
class mechanics
最新推荐文章于 2021-06-29 17:28:47 发布