C++(day6)
一、思维导图
二、搭建一个货币的场景,创建一个名为 RMB 的类,该类具有整型私有成员变量 yuan(元)、jiao(角)和 fen(分),并且具有以下功能;
(1)重载算术运算符,和一,使得可以对两个 RMB 刘象进行加法和减法运算,并返回一个新的RMB 对象作为结果。
(2)重载关系运算符>,判断一个 RMB 刘象是否大于另一个 RMB 耐象,并返回 true 或 false。
(3)重载前置減減运算符一,使得每次调用时 RMB 列象的yuan、 jao 和 fen 分別减1
(4)重载后置减減运算符一,使得每次调用时 RMB 對象的yuan.jao 和 fen 分別减1
(5)另外,RMB 类还包含一个静态整型成员安量 count,用于记录当前已创建的 RMB 对象的数量。每当创建一个新的 RMB对象时,count 应该自增1:每当销毁一个 RMB 对象时,count 应该自减1.
要求,需要在main 函数中测试上述RMB 类的功能
#include <iostream>using namespace std;class RMB
{
private:int yuan;int jiao;int fen;static int count;
public:RMB(){count++;}RMB(int yuan,int jiao,int fen):yuan(yuan),jiao(jiao),fen(fen){count++;}~RMB(){count--;}const RMB operator+(const RMB &R) const{RMB temp;temp.yuan=this->yuan+R.yuan;temp.jiao=this->jiao+R.jiao;temp.fen=this->fen+R.fen;return temp;}const RMB operator-(const RMB &R) const{RMB temp;if((temp.fen=this->fen-R.fen)>=0){if((temp.jiao=this->jiao-R.jiao)>=0){temp.yuan=this->yuan-R.yuan;return temp;}else{temp.jiao+=10;temp.yuan=this->yuan-R.yuan-1;return temp;}}else{temp.fen+=10;if((temp.jiao=this->jiao-R.jiao-1)>=0){temp.yuan=this->yuan-R.yuan;return temp;}else{temp.jiao+=10;temp.yuan=this->yuan-R.yuan-1;return temp;}}}bool operator>(const RMB &R) const{if(this->yuan>R.yuan){return true;}else if(this->yuan==R.yuan){if(this->jiao>R.jiao){return true;}else if(this->jiao==R.jiao){if(this->fen>R.fen){return true;}elsereturn false;}elsereturn false;}elsereturn false;}RMB &operator--(){--this->yuan;--this->jiao;--this->fen;return *this;}RMB &operator--(int){static RMB temp;temp.yuan=this->yuan--;temp.jiao=this->jiao--;temp.fen=this->fen--;return temp;}void show(){cout<<this->yuan<<"元"<<this->jiao<<"角"<<this->fen<<"分"<<endl;}
};int RMB::count=0;int main()
{RMB p1(102,8,7);cout<<"p1=";p1.show();RMB p2(88,4,7);cout<<"p2=";p2.show();RMB p3=p1+p2;cout<<"p3=p1+p2=";p3.show();RMB p4=p1-p2;cout<<"p4=p1-p2";p4.show();RMB p5=p2-p1;cout<<"p5=p2-p1=";p5.show();if(p1>p2){cout<<"p1>p2"<<endl;}elsecout<<"p1<=p2"<<endl;RMB p6=--p1;cout<<"p6=--p1=";p6.show();RMB p7=p2--;cout<<"p7=p2--=";p7.show();return 0;
}
测试结果