定义一个人民币的类(重载+、-、+=、++、输入输出流).cpp 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #include<iostream>
  2. #include<iomanip>
  3. using namespace std;
  4. class RMB {
  5. private:
  6. int yuan, jiao, fen;
  7. public:
  8. RMB(int yuan = 0, int jiao = 0, int fen = 0) : yuan(yuan), jiao(jiao), fen(fen) {}
  9. friend istream& operator>>(istream& in, RMB& r) {
  10. cout << "请分别输入元、角、分(整数之间用空格或回车间隔):" << endl;
  11. in >> r.yuan >> r.jiao >> r.fen;
  12. return in;
  13. }
  14. friend ostream& operator<<(ostream& out, const RMB& r) {
  15. int totalFen = r.yuan * 100 + r.jiao * 10 + r.fen;
  16. int yuan = totalFen / 100;
  17. int jiao = (totalFen / 10) % 10;
  18. int fen = totalFen % 10;
  19. out << "¥ " << yuan << "." << jiao << fen;
  20. return out;
  21. }
  22. RMB operator+(const RMB& r) const {
  23. RMB result;
  24. result.fen = fen + r.fen;
  25. result.jiao = jiao + r.jiao + result.fen / 100;
  26. result.fen %= 100;
  27. result.yuan = yuan + r.yuan + result.jiao / 10;
  28. result.jiao %= 10;
  29. return result;
  30. }
  31. RMB& operator+=(const RMB& r) {
  32. fen += r.fen;
  33. jiao += r.jiao + fen / 100;
  34. fen %= 100;
  35. yuan += r.yuan + jiao / 10;
  36. jiao %= 10;
  37. return *this;
  38. }
  39. RMB operator-(const RMB& r) const {
  40. RMB result;
  41. int totalFen = (yuan * 10 + jiao) * 10 + fen;
  42. int rTotalFen = (r.yuan * 10 + r.jiao) * 10 + r.fen;
  43. totalFen -= rTotalFen;
  44. if (totalFen < 0)
  45. totalFen = 0;
  46. result.fen = totalFen % 10;
  47. totalFen /= 10;
  48. result.jiao = totalFen % 10;
  49. totalFen /= 10;
  50. result.yuan = totalFen;
  51. return result;
  52. }
  53. RMB& operator++() {
  54. fen++;
  55. if (fen >= 100) {
  56. fen -= 100;
  57. jiao++;
  58. }
  59. if (jiao >= 10) {
  60. jiao -= 10;
  61. yuan++;
  62. }
  63. return *this;
  64. }
  65. };
  66. int main()
  67. {
  68. RMB r1(14, 5 ,7),r2,r3; //定义三个人民币的对象, 其中两个调用缺省的构造, 构造为0
  69. cout<<"请输入一个人民币数值: \n";
  70. cin>>r2; //调用重载的输入流输入对象的数值
  71. r3=r1+r2; //调用重载的加法运算符
  72. cout<<r1<<" + "<<r2<<" = "<<r3<<endl;
  73. cout<<r3<<" + "<<r1<<" = ";
  74. r3+=r1; //调用重载运算符
  75. cout<<r3<<endl;
  76. cout<<r3<<" - "<<r1<<" = ";
  77. r3=r3-r1; //调用重载运算符
  78. cout<<r3<<endl;
  79. cout<<r3<<" + "<<"¥ 0.01 = ";
  80. ++r3; //调用重载运算符
  81. cout<<r3<<endl;
  82. return 0;
  83. }