静态数据成员/静态成员函数/运算符重载

搭建一个货币的场景,创建一个名为 RMB 的类,该类具有整型私有成员变量 yuan(元)、jiao(角)和 fen(分),并且具有以下功能:

(1)重载算术运算符 + 和 -,使得可以对两个 RMB 对象进行加法和减法运算,并返回一个新的 RMB 对象作为结果。

(2)重载关系运算符 >,判断一个 RMB 对象是否大于另一个 RMB 对象,并返回 true 或 false。

(3)重载前置减减运算符 --,使得每次调用时 RMB 对象的 yuan、jiao 和 fen 分别减 1

(4)重载后置减减运算符 --,使得每次调用时 RMB 对象的 yuan、jiao 和 fen 分别减 1

(5)另外, RMB 类还包含一个静态整型成员变量 count,用于记录当前已创建的 RMB 对象的数量。每当创建一个新的 RMB 对象时,count 应该自增 1;每当销毁一个 RMB 对象时,count 应该自减 1。

要求,需要在main 函数中测试上述RMB 类的功能。

代码:
#include <iostream>

using namespace std;
class RMB{
    friend const RMB operator+(const RMB &L,const RMB &R);
    friend const RMB operator-(const RMB &L,const RMB &R);
    friend bool operator>(const RMB &L,const RMB &R);
    friend RMB &operator--(RMB &O);
private:
    int yuan;
    int mao;
    int fen;
    static int count;
public:
    RMB(){
    }
    RMB(int yuan,int mao,int fen):yuan(yuan),mao(mao),fen(fen){
        count++;
    }
    RMB(const RMB &other):yuan(other.yuan),mao(other.mao),fen(other.fen){
        count++;
    }
    RMB &operator=(const RMB &other){
        if(this!=&other){
            yuan=other.yuan;
            mao=other.mao;
            fen=other.fen;
            count++;
        }
        return *this;
    }
    ~RMB(){}
    static void show_count(){
        cout << "当前RMB数量" << count << endl;
    }
    const RMB operator--(int){
        RMB temp;
        temp.yuan=yuan--;
        temp.mao=mao--;
        temp.fen=fen--;
        return temp;
    }
    void show(){
        cout << yuan << "元" << mao << "毛" << fen << "分" << endl;
    }
};
int RMB::count=0;
//全局函数实现运算符重载
const RMB operator+(const RMB &L,const RMB &R){
    RMB temp;
    temp.yuan=L.yuan+R.yuan;
    temp.mao=L.mao+R.mao;
    temp.fen=L.fen+R.fen;
    return temp;

}
const RMB operator-(const RMB &L,const RMB &R){
    RMB temp;
    temp.yuan=L.yuan-R.yuan;
    temp.mao=L.mao-R.mao;
    temp.fen=L.fen-R.fen;
    return temp;

}
bool operator>(const RMB &L,const RMB &R){
    if(L.yuan > R.yuan){
        return true;
    }else if(L.yuan == R.yuan && L.mao > R.mao){
        return true;
    }else if(L.yuan == R.yuan && L.mao == R.mao && L.fen > R.fen){
             return true;
         }else{
        return false;
    }
}
RMB &operator--(RMB &O){
    --O.yuan;
    --O.mao;
    --O.fen;
    return O;
}
int main()
{
    RMB R1(5,1,1);
    RMB R2(5,3,3);
    if(R2>R1){
       cout << "R2 > R1" << endl;
    }
    RMB R3;
    R3=--R2;
    RMB R4;
    R4=R2--;
    RMB R5=--R2;
    R5.show();
    RMB::show_count();
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值