赞
踩
作业:
思维导图:
作业题:
搭建一个货币的场景,创建一个名为 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{
- private:
- int yuan;
- int jiao;
- int fen;
- static int count;
-
- public:
- RMB(int y,int j,int f):yuan(y),jiao(j),fen(f){
- ++count;
- }
- RMB operator+(const RMB& other){
- int total=yuan*100+jiao*10+fen+other.yuan*100+other.jiao*10+other.fen;
- int newyuan=total/100;
- int newjiao=(total%100)/10;
- int newfen=total%10;
- return RMB(newyuan,newjiao,newfen);
-
- }
- RMB operator-(const RMB& other){
- int total=yuan*100+jiao*10+fen-other.yuan*100-other.jiao*10-other.fen;
- int newyuan=total/100;
- int newjiao=(total%100)/10;
- int newfen=total%10;
- return RMB(newyuan,newjiao,newfen);
- }
- bool operator>(const RMB& other){
- int total1=yuan*100+jiao*10+fen;
- int total2=other.yuan*100+other.jiao*10+other.fen;
- return total1>total2;
- }
- RMB& operator--(){
- if(fen>0){
- --fen;
- }else if(jiao>0){
- --jiao;
- fen=9;
- }else if(yuan>0){
- --yuan;
- jiao=9;
- fen=9;
- }
- return *this;
- }
- const RMB operator--(int){
- RMB temp=*this;
- --(*this);
- return temp;
-
- }
- static int getcount(){
- return count;
- }
- ~RMB(){
- count--;
- }
- void show(){
- cout<<yuan<<" "<<jiao<<" "<<fen<<endl;
- }
- };
-
- int RMB::count=0;
- int main()
- {
- RMB R1(1,3,5);
- RMB R2(2,2,8);
- RMB R3=R1+R2;
- R3.show();
- RMB R4=R2-R1;
- R4.show();
- bool result=R2>R1;
- cout<<result<<endl;
- RMB R5=--R1;
- R5.show();
- RMB R6=R2--;
- R6.show();
- R2.show();
-
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。