C++操作符重载及实现简单的复数类Complex

操作符重载:
重载操作符是具有特殊函数名的函数,关键字operator后面接需要定义的操作符符号。
操作符重载也是一个函数,具有返回值和形参表。它的形参数目与操作符的操作数目相同。
函数调用操作符可以接受任意数目的操作数。
使用运算符重载可以提高代码的可读性。
返回类型 operate 操作符(参数列表);
可被重载操作符

不可被重载操作符

建议:
使用重载操作符,可以令程序更自然、更直观,而滥用操作符重载会使得类难以理解,在实践中很少发生明显的操作符重载滥用。但有些程序员会定义operator+来执行减法操作,当一个重载操作符不明确时,给操作符取一个名字更好,对于很少用的操作,使用命名函数通常比用操作符好,如果不是普通操作,没有必要为简洁而用操作符。

#include<iostream>
using namespace std;

class Complex
{
public:
    //构造函数
    Complex(int real = 0, int image = 0)
        :_real(real)
        ,_image(image)
    {}

    //析构函数
    ~Complex()
    {}

    //拷贝构造函数
    Complex(Complex &c)
        :_real(c._real)
        ,_image(c._image)
    {}

    //显示负数的实部和虚部
    void display()
    {
        cout << "real:" << _real << endl;
        cout << "image:" << _image << endl;
    }
    //运算符重载
    Complex& operator=(const Complex& d)
    {
        _real = d._real;
        _image = d._image;
        return *this;
    }

    bool operator == (const Complex& d)
    {
        return (_real == d._real) && (_image == d._image);
    }

    bool operator != (const Complex& d)
    {
        return (_real != d._real) && (_image != d._image);
    }

    Complex operator+(const Complex& d)
    {
        Complex temp(0, 0);
        temp._real = _real + d._real;
        temp._image = _image + d._image;
        return temp;
    }

    Complex operator-(const Complex& d)
    {
        Complex temp(0, 0);
        temp._real = _real - d._real;
        temp._image = _image - d._image;
        return temp;
    }

    Complex& operator+=(const Complex& d)
    {
        _real += d._real;
        _image += d._image;
        return *this;
    }

    Complex& operator-=(const Complex& d)
    {
        _real -= d._real;
        _image -= d._image;
        return *this;
    }

    //前置++
    Complex operator++()
    {
        _real++;
        _image++;
        return *this;
    }

    //后置++ 
    Complex operator++(int)
    {
        Complex temp = *this;
        _real++;
        _image++;
        return temp;
    }

    //前置--
    Complex operator--()
    {
        _real--;
        _image--;
        return *this;
    }

    //后置--
    Complex operator--(int)
    {
        Complex temp = *this;
        _real--;
        _image--;
        return temp;
    }
private:
    int _real;
    int _image;
};

int main()
{
    Complex d1(5, 10);
    Complex d2(7, 10);
    d2.display();
    system("pause");
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fly_bit

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值