学习记录:
练习题:
#include <iostream> using namespace std; class RMB { private: int yuan; int jiao; int fen; static int count; public: RMB(int yuan = 0, int jiao = 0, int fen = 0) : yuan(yuan),jiao(jiao),fen(fen){ ++count;} ~RMB(){--count;} static void getcountNUM() { cout << "当下账户数量:" << count << endl; } const RMB operator+(const RMB &c)const;//成员函数实现 + 重载 const RMB operator-(const RMB &c)const;//成员函数实现 - 重载 bool operator>(const RMB &c)const;//成员函数实现 > 重载 RMB &operator--(); //成员函数实现 前置-- 重载 返回一个左值 RMB operator--(int);//成员函数实现 后置-- 重载 返回一个右值 void show() { cout << yuan << "元" << jiao << "角" << fen <<"分" << endl; } }; int RMB::count = 0; //静态数据成员需要在类外进行初始化!!!! const RMB RMB::operator+(const RMB &c)const { RMB temp; temp.yuan = this->yuan + c.yuan; temp.jiao = this->jiao + c.jiao; temp.fen = this->fen + c.fen; return temp ; } const RMB RMB::operator-(const RMB &c)const//成员函数实现 - 重载 { RMB temp; temp.yuan = this->yuan - c.yuan; temp.jiao = this->jiao - c.jiao; temp.fen = this->fen - c.fen; return temp ; } bool RMB::operator>(const RMB &c)const { bool ret = this->yuan > c.yuan || (this->yuan == c.yuan && this->jiao > c.jiao )|| (this->yuan == c.yuan && this->jiao == c.jiao && this->fen > c.fen); return ret; } RMB &RMB::operator--() //前置-- 返回一个左值 { --this->yuan; --this->jiao; --this->fen; return *this; } RMB RMB::operator--(int) //后置-- 返回一个右值 { RMB temp; temp.fen = this->fen--; temp.jiao = this->jiao--; temp.yuan = this->yuan--; return temp; } int main() { RMB c1 (101,6,5); RMB c2(50,5,4); RMB c3 = c1 + c2; c3.show(); if(c1 > c2) { cout << "c1 > c2" << endl; } c2 = c1--; c2.show(); c1.show(); c2 = --c1; c2.show(); c1.show(); RMB::getcountNUM(); // 3个 RMB *c4 = new RMB(25,5,6); RMB::getcountNUM(); //4个 delete c4; c4 = nullptr; RMB::getcountNUM(); //3个 return 0; }