码迷,mamicode.com
首页 > 编程语言 > 详细

【C++】 复数类操作

时间:2016-01-20 22:50:35      阅读:302      评论:0      收藏:0      [点我收藏+]

标签:复数类

复数的概念我们高中已经接触过,包含是实部和虚部,

For example:2i + 3J;实部和虚部值可为整型,亦可浮点型,那在此实现一下简单的复数类的操作


代码如下:

class Complex
{
public:

    Complex(double real,double imag)
    {
        _real = real;
        _imag = imag;
    }

    Complex(const Complex& c)
    {
        _real = c._real;
        _imag = c._imag;
    }

    ~Complex()
    {
        
    }
    
    Complex& operator=(const Complex& c)
    {
        if(&c != this)
        {
        this->_real = c._real;
        this->_imag = c._imag;
        }
        return *this;
    }
    
    Complex operator+(const Complex& c)
    {
        Complex ret(*this);// + 运算返回运算后的值

        ret._real += c._real;
        ret._imag += c._imag;
        
        return ret;
    }

    Complex& operator++() // 前置++ , 当外面需要此返回值时,需要加&
    {
        this->_real += 1;
        this->_imag += 1;

        return *this;
    }

    Complex operator++(int) // 后置++ ,当外面不需要此返回值时,无需加&
    {
        Complex tmp(*this);//后置++返回原来的值,故定义一个临时变量保存起来

        this->_real += 1;
        this->_imag += 1;

        return tmp;
    }

    
    Complex& operator+= (const Complex& c)
    {
        this->_real = this->_real + c._real;
        this->_imag = this->_imag + c._imag;

        return *this;
    }

    inline bool operator==(const Complex& c)
    {
        return (_real == c._real 
                && _imag == c._imag);
    }

    inline bool operator>(const Complex& c)
    {
        return (_real > c._real
                && _imag > c._imag);
    }

    inline bool operator>=(const Complex& c)
    {
        
        //return (_real >= c._real
        //        && _imag >= c._imag);

        return (*this > c) || (*this == c);//直接使用上面实现重载符 > 和 ==

    }

    inline bool operator<=(const Complex& c)
    {
        //return (_real <= c._real
        //        && _imag <= c._imag);

        return !(*this > c);//直接使用上面实现重载符 > 
    
    }

    bool operator<(const Complex& c)
    {
        return !(*this > c) || (*this == c);//直接使用上面实现重载符 >= 
    }

    inline void Display()
    {
        cout<<_real<<"-"<<_imag<<endl;
    }

private:

    double _real;
    double _imag;

};


测试单元:(偷懒就在main函数里测试,可以单独封装一个函数进行测试)

int main()
{
    Complex c(1,2);
    Complex c1(c);

    //c1.Display();
    //Complex ret = ++c1;
    //Complex ret = c1++;
    //ret.Display();
    Complex ret(c1);
    ret.Display();

    return 0;
}




本文出自 “Vs吕小布” 博客,谢绝转载!

【C++】 复数类操作

标签:复数类

原文地址:http://survive.blog.51cto.com/10728490/1736943

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!