运算符重载 加减乘除

#include <iostream>
using namespace std;//运算符的重载
class A
{
public:
    A(int x)
    {
        a = x;
    }
    ~A()
    {

    }
    //运算符重载函数+=;加法
    A operator +=(const A&b)
    {
        this->a = this->a+ b.a;
        return this->a;
    }

    A operator -=(const A&b)
    {
    //运算符重载函数-=;减法
        this->a = this->a- b.a;
        return this->a;
    }

    A operator *=(const A&b)
    {
    //运算符重载函数*=;乘法
        this->a = this->a* b.a;
        return this->a;
    }
    A operator /=(const A&b)
    {
    //运算符重载函数/=;除法
        this->a = this->a/ b.a;
        return this->a;
    }
    int a;
};
void main()
{
    A a(1);
    A b(2);
    A c(3);
    A d(4);
    A e(5);
    b += a;//现在才可以编译通过,进行加减乘除运算
    c -= a;
    d *= a;
    e /= a;
    cout<<"运算符重载加法结果是:"<<b.a<<endl;
    cout<<"运算符重载减法结果是:"<<c.a<<endl;
    cout<<"运算符重载乘法结果是:"<<d.a<<endl;
    cout<<"运算符重载除法结果是:"<<e.a<<endl;
}

使用重载函数:

    A operator +=(const A&b)
    {
        this->a = this->a+ b.a;
        return this->a;
    }


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值