zoukankan      html  css  js  c++  java
  • 极其简单的复数类,只是不想再推演一遍复数四则运算

    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());
    }
  • 相关阅读:
    c++中的内存管理【转载】
    c++中dynamic_cast、static_cast、reinterpret_cast和const_cast作用
    c++中的顶层const和底层const
    c++赋值操作符需要确保自我赋值的安全性问题
    二分法查找
    Servlet基础总结
    java 正则表达式:有丶东西
    HTTP协议初步认识
    Java synchronized到底锁住的是什么?
    ECMA Script 6新特性之解构赋值
  • 原文地址:https://www.cnblogs.com/wuOverflow/p/5019979.html
Copyright © 2011-2022 走看看