思维导图
代码
#include <iostream>
using namespace std;
//创建一个RMB类
class RMB
{
friend const RMB operator+(const RMB &p1, const RMB &p2);
friend const RMB operator-(const RMB &p1, const RMB &p2);
friend bool operator>(const RMB &p1, const RMB &p2);
friend RMB &operator--(RMB &other);
friend const RMB operator--(RMB &other, int);
private:
int yuan;
int jiao;
int fen;
static int count;
public:
//无参构造函数
RMB()
{
count++;
}
//有参构造函数
RMB(int yuan,int jiao,int fen):yuan(yuan),jiao(jiao),fen(fen)
{
count++;
}
//拷贝构造函数
RMB(const RMB &other):yuan(other.yuan),jiao(other.jiao),fen(other.fen)
{
count++;
}
//析构函数
~RMB()
{
count--;
}
//静态成员函数
static int Count()
{
return count;
}
void show()
{
cout << yuan << "元" << jiao << "角" << fen << "分" << endl;
}
};
//静态变量初始化
int RMB::count=0;
//+运算符重载
const RMB operator+(const RMB &p1, const RMB &p2)
{
RMB p;
p.yuan = p1.yuan + p2.yuan;
p.fen = p1.fen + p2.fen;
p.jiao = p1.jiao + p2.jiao;
return p;
}
//-运算符重载
const RMB operator-(const RMB &p1, const RMB &p2)
{
RMB p;
p.yuan = p1.yuan - p2.yuan;
p.fen = p1.fen - p2.fen;
p.jiao = p1.jiao - p2.jiao;
return p;
}
//>运算符重载
bool operator>(const RMB &p1, const RMB &p2)
{
if(p1.yuan*100+p1.jiao*10+p1.fen > p2.yuan*100+p2.jiao*10+p2.fen)
{
return true;
}
else
{
return false;
}
}
//前自减运算符重载
RMB &operator--(RMB &other)
{
--other.yuan;
--other.jiao;
--other.fen;
return other;
}
//后自减运算符重载
const RMB operator--(RMB &other, int)
{
RMB p;
p.yuan = other.yuan--;
p.jiao = other.jiao--;
p.fen = other.fen--;
return p;
}
int main()
{
RMB r1(100,9,1);
RMB r2(2000,1,9);
cout << "-------重载加法-------" << endl;
RMB r3 = r1 + r2;
r3.show();
cout << "-------重载减法-------" << endl;
RMB r4 = r1 - r2;
r4.show();
cout << "-------重载大于-------" << endl;
if(r3 > r4){cout << "true" << endl;}
cout << "-------重载前自减-------" << endl;
RMB r5 = --r4;
r4.show();
r5.show();
cout << "-------重载后自减-------" << endl;
RMB r6=r5--;
r5.show();
r6.show();
cout << " " << endl;
cout << "RMB对象个数:" << RMB::Count() << endl;
return 0;
}
结果