实现运算符重载
#include <iostream>
using namespace std;
class RMB
{
private:
int yuan;
int jiao;
int fen;
static int count;
public:
RMB()
{
count++;
cout << "初级" << this << endl;
}
RMB(int a,int b,int c):yuan(a),jiao(b),fen(c)
{
count++;
cout << "构造函数" <<this << endl;
}
RMB &operator=(const RMB &other)
{
if(this!=&other)
{
yuan=other.yuan;jiao=other.jiao;fen=other.fen;
// count++;
}
cout << "赋值" << endl;
return *this;
}
const RMB operator+(const RMB &r) const
{
RMB temp;
temp.yuan=yuan+r.yuan;
temp.jiao=jiao+r.jiao;
temp.fen=fen+r.fen;
temp.show();
return temp;
}
const RMB operator-(const RMB &r) const
{
RMB temp;
temp.yuan=yuan-r.yuan;
temp.jiao=jiao-r.jiao;
temp.fen=fen-r.fen;
return temp;
}
bool operator>(RMB &r)
{
if(yuan>r.yuan&&jiao>r.jiao&&fen>r.fen)
{
return true;
}
else
{
return false;
}
}
RMB operator--()
{
RMB temp;
temp.yuan=--yuan;
temp.jiao=--jiao;
temp.fen=--fen;
return temp;
}
RMB operator--(int)
{ RMB temp;
temp.yuan=yuan--;
temp.jiao=jiao--;
temp.fen=fen--;
return temp;
}
void show()
{
cout << yuan << "\t"\
<< jiao << "\t"\
<< fen << this <<endl;
}
~RMB()
{
count--;
cout << "剩余RMB数量为" << count << '\t' << this << endl;
}
};
int RMB::count = 0;
int main()
{
RMB s1(4,4,4); //定义初始化“=”优先级大于重载
RMB s2(2,2,2); //初始化新类,局部结构体的,新类延用已申请空间,全局另设新空间
RMB s3=s1+s2;
RMB s4=s1-s2;
s3.show();
s4.show();
RMB s5=s3--;
RMB s6=--s3;
s5.show();
s6.show();
bool q=s1>s2;
cout << q << endl;
cout << "Hello World!" << endl;
return 0;
}
实现效果