当前位置:   article > 正文

c++ 6.11

c++ 6.11

作业:

思维导图:

作业题:

搭建一个货币的场景,创建一个名为 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 类的功能。

  1. #include <iostream>
  2. using namespace std;
  3. class RMB{
  4. private:
  5. int yuan;
  6. int jiao;
  7. int fen;
  8. static int count;
  9. public:
  10. RMB(int y,int j,int f):yuan(y),jiao(j),fen(f){
  11. ++count;
  12. }
  13. RMB operator+(const RMB& other){
  14. int total=yuan*100+jiao*10+fen+other.yuan*100+other.jiao*10+other.fen;
  15. int newyuan=total/100;
  16. int newjiao=(total%100)/10;
  17. int newfen=total%10;
  18. return RMB(newyuan,newjiao,newfen);
  19. }
  20. RMB operator-(const RMB& other){
  21. int total=yuan*100+jiao*10+fen-other.yuan*100-other.jiao*10-other.fen;
  22. int newyuan=total/100;
  23. int newjiao=(total%100)/10;
  24. int newfen=total%10;
  25. return RMB(newyuan,newjiao,newfen);
  26. }
  27. bool operator>(const RMB& other){
  28. int total1=yuan*100+jiao*10+fen;
  29. int total2=other.yuan*100+other.jiao*10+other.fen;
  30. return total1>total2;
  31. }
  32. RMB& operator--(){
  33. if(fen>0){
  34. --fen;
  35. }else if(jiao>0){
  36. --jiao;
  37. fen=9;
  38. }else if(yuan>0){
  39. --yuan;
  40. jiao=9;
  41. fen=9;
  42. }
  43. return *this;
  44. }
  45. const RMB operator--(int){
  46. RMB temp=*this;
  47. --(*this);
  48. return temp;
  49. }
  50. static int getcount(){
  51. return count;
  52. }
  53. ~RMB(){
  54. count--;
  55. }
  56. void show(){
  57. cout<<yuan<<" "<<jiao<<" "<<fen<<endl;
  58. }
  59. };
  60. int RMB::count=0;
  61. int main()
  62. {
  63. RMB R1(1,3,5);
  64. RMB R2(2,2,8);
  65. RMB R3=R1+R2;
  66. R3.show();
  67. RMB R4=R2-R1;
  68. R4.show();
  69. bool result=R2>R1;
  70. cout<<result<<endl;
  71. RMB R5=--R1;
  72. R5.show();
  73. RMB R6=R2--;
  74. R6.show();
  75. R2.show();
  76. return 0;
  77. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/707054
推荐阅读
相关标签
  

闽ICP备14008679号