C++运算符重载

如果要处理一个虚数,我们可以定义一个虚数类,要让其实现运算,我们还需要定义其方法。
#include<stdio.h>
using namespace std;
class Complex
{
public:
    Complex(double r=0,double i =0){real=r;image=i;}
    double Real(){return real;}
    double Image(){return image;}
    Complex add(Complex &c)         //定义加法
    {
        real+=c.real;
        image+=c.image;
        return *this;
    };

private:
    double real;
    double image;
};
int main()
{
    Complex c1(1,2);
    Complex c2(1,3);
    c1.add(c2);
    printf("%f %f",c1.Real(),c1.Image());
    return 0;
}

事实上还有另一种减少代码量的方法,即重载运算符,这种方法不仅使看起来简洁易懂,而且与预定义的运算保持一致。

#include<stdio.h>
using namespace std;
class Complex
{
public:
    Complex(double r=0,double i =0){real=r;image=i;}
    double Real(){return real;}
    double Image(){return image;}
    Complex operator + (Complex &c) const        //定义加法
    {
        Complex C(real+c.real,image+c.image);
        return C;
    };
    Complex operator =(Complex c)
    {
        this->real=c.real;
        this->image=c.image;
        return *this;
    }

private:
    double real;
    double image;
};
int main()
{
    Complex c1(1,2);
    Complex c2(1,3);
    Complex c3;
    c3=c1+c2;
    printf("%f %f",c3.Real(),c3.Image());
    return 0;
}

重载"=="操作符

int operator ==(Complex& c) ;
int operator ==(double d) const;
int Complex:: operator ==(Complex& c)
{
    if(c.Real()==this->real&&c.Image()==this->image)
        return 1;
    else
        return 0;
}
int Complex:: operator ==(double d) const
{
    if(!this->image&&d==this->real)
        return 1;
    else
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值