1:运算符重载
1 RMB.h 2 #ifndef RMB_H 3 #define RMB_H 4 5 #include <bits/stdc++.h> 6 using namespace std; 7 class RMB 8 { 9 public: 10 RMB(); 11 RMB(int, int); 12 virtual ~RMB(); 13 void display() 14 { 15 cout << "RMB:" << yuan << "."; 16 if(jf < 10) 17 { 18 cout << "0"; 19 } 20 cout << jf << endl; 21 } 22 friend RMB operator+(const RMB&, const RMB&);//作为友元函数的元素符重载 23 friend bool operator>(const RMB&, const RMB&); 24 int Getjf() { return jf; } 25 void Setjf(int val) { jf = val; } 26 int Getyuan() { return yuan; } 27 void Setyuan(int val) { yuan = val; } 28 RMB operator+(const RMB& s)//作为成员函数的运算符重载 29 { 30 int c = this->jf + s.jf; 31 int d = this->yuan + s.yuan; 32 return RMB(c,d); 33 } 34 protected: 35 36 private: 37 int jf; 38 int yuan; 39 }; 40 41 #endif // RMB_H 42 RMB.cpp 43 /* 44 * 文件名: 45 * 描 述: 46 * 作 者: 47 * 时 间: 48 * 版 权: 49 */#include "RMB.h" 50 #include <bits/stdc++.h> 51 using namespace std; 52 RMB::RMB() 53 { 54 cout << "RMB construction" << endl; 55 } 56 RMB::RMB(int _yuan, int _jf):yuan(_yuan),jf(_jf) 57 { 58 cout << "RMB(int, int) construction" << endl; 59 } 60 RMB::~RMB() 61 { 62 cout << "RMB destruction" << endl; 63 } 64 65 RMB operator+(const RMB& val1,const RMB& val2)//重载加运算符 66 { 67 int jf = val1.jf + val2.jf; 68 int yuan = val1.yuan + val2.yuan; 69 if(jf > 99){ 70 yuan++; 71 jf-=100; 72 } 73 return RMB(yuan, jf);//局部对象不可以返回引用 74 } 75 76 bool operator>(const RMB& val1, const RMB& val2)//判断大小 77 { 78 bool ret =false; 79 if(val1.yuan > val2.yuan) 80 { 81 ret = true; 82 }else if(val1.yuan == val2.yuan){ 83 if(val1.jf > val2.jf) 84 { 85 ret = true; 86 } 87 } 88 return ret; 89 } 90 91 main.cpp 92 #include <iostream> 93 #include "RMB.h" 94 using namespace std; 95 96 int main() 97 { 98 99 RMB rmb1(12,13); 100 RMB rmb2(9,9); 101 cout << (rmb1 > rmb2) << endl; 102 RMB rmb3 = rmb1 + rmb2; 103 cout << rmb3.Getyuan() << " " << rmb3.Getjf() << endl; 104 rmb3.display(); 105 return 0; 106 }