Exceptional C++

【Exceptional C++(9)】CLASS技术

2018-01-29  本文已影响4人  downdemo

问题

class Complex
{
public:
    Complex(double real, double imaginary = 0)
      :  _real(real), _imaginary(imaginary)
    {}
    void operator+(Complex other)
    {
        _real = _real + other._real;
        _imaginary = _imaginary + other._imaginary;
    }
    void operator<<(ostream os)
    {
        os << "(" << _real << "," << _imaginary << ")";
    }
    Complex operator++()
    {
        ++_real;
        return *this;
    }
    Complex operator++(int)
    {
        Complex temp = *this;
        ++_real;
        return temp;
    }
private:
    double _real, _imaginary;
};

解答

    Complex(double real, double imaginary = 0)
      :  _real(real), _imaginary(imaginary)
    {}
    void operator+(Complex other)
    {
        _real = _real + other._real;
        _imaginary = _imaginary + other._imaginary;
    }
T& T::operator+=(const T& other)
{
    // ...
    return *this;
}
const T operator+(const T& a, const T& b)
{
    T temp(a);
    temp += b;
    return temp;
}
    Complex operator++()
    {
        ++_real;
        return *this;
    }
    Complex operator++(int)
    {
        Complex temp = *this;
        ++_real;
        return temp;
    }
class Complex
{
public:
    explicit Complex(double real, double imaginary = 0)
      :  real_(real), imaginary_(imaginary)
    {}
    // 定义operator+=,将operator+设为non-member
    Complex& operator+=(const Complex& other)
    {
        real_ += other.real_;
        imaginary_ += other.imaginary_;
        return *this;
    }
    Complex& operator++()
    {
        ++real_;
        return *this;
    }
    Complex operator++(int)
    {
        Complex temp(*this);
        ++*this;
        return temp;
    }
    // 定义Print
    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);  
}
上一篇下一篇

猜你喜欢

热点阅读