极其简单的复数类,只是不想再推演一遍复数四则运算

class Complex
{
private:
    double real_ = 0.0;
    double imag_ = 0.0;
public:
    Complex() = default;
    explicit Complex(double real, double imag):
        real_(real), imag_(imag)
    {}
    
    Complex(const Complex& other)
    {
        real_ = other.real_;
        imag_ = other.imag_;
    }
    
    Complex(Complex&& other)
    {
        real_ = std::move(other.real_);
        imag_ = std::move(other.imag_);
    }
    
    Complex& operator=(const Complex& other)
    {
        real_ = other.real_;
        imag_ = other.imag_;
        return *this;
    }
    
    Complex& operator=(Complex&& other)
    {
        real_ = std::move(other.real_);
        imag_ = std::move(other.imag_);
        return *this;
    }
    
    double real() const
    {
        return real_;
    }
    
    double imag() const
    {
        return imag_;
    }
    
    void setReal(double newReal)
    {
        real_ = newReal;
    }
    
    void setImag(double newImag)
    {
        imag_ = newImag;
    }
};

Complex operator+(const Complex& c1, const Complex& c2)
{
    return Complex((c1.real() + c2.real()), (c1.imag() + c2.imag()));
}
Complex operator-(const Complex& c1, const Complex& c2)
{
    return Complex((c1.real() - c2.real()), (c1.imag() - c2.imag()));
}
Complex operator*(const Complex& c1, const Complex& c2)
{
    double const real = c1.real() * c2.real() - c1.imag() * c2.imag();
    double const imag = c1.real() * c2.imag() + c1.imag() * c2.real();
    return Complex(real, imag);
}
Complex operator/(const Complex& c1, const Complex& c2)
{
    const double denominator = c2.real() * c2.real() + c2.imag() * c2.imag();
    Complex tmpComplex(c2.real(), -c2.imag());
    Complex&& result = c1 * tmpComplex;
    result.setReal(result.real() / denominator);
    result.setImag(result.imag() / denominator);
    return result;
}
void print(const Complex& complex)
{
    std::printf("(%.1f, %.1f)", complex.real(), complex.imag());
}
原文地址:https://www.cnblogs.com/wuOverflow/p/5019979.html