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

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