本文主要是介绍day5 C++,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#include <iostream>
using namespace std;
class RMB
{
private:
int yuan;
int jiao;
int fen ;
static int count; //记录个数 静态数据成员
public:
//无参构造
RMB()
{
cout << "RMB::无参构造" <<endl;
count++;
}
RMB(int yuan ,int jiao ,int fen):yuan(yuan),jiao(jiao),fen(fen)
{
cout << "RMB::有参构造" <<endl;
count++;
}
RMB(const RMB &other):yuan(other.yuan),jiao(other.jiao),fen(other.fen)
{
count++;
}
~RMB()
{
count--;
}
//重载+
const RMB operator+(const RMB &other)
{
int last1=yuan*100+jiao *10+fen; // 当前对象的分
int last2=other.yuan *100+other.jiao*10+other.fen;
int new_last=last1+last2;
int new_yuan=new_last/100;
new_last%=100;
int new_jiao=new_last/10;
int new_fen=new_last/10;
return RMB(new_yuan,new_jiao,new_fen);
}
//重载-
const RMB operator-(const RMB &other)
{
int last1=yuan*100+jiao *10+fen; // 当前对象的分
int last2=other.yuan *100+other.jiao*10+other.fen;
int new_last=last1-last2;
int new_yuan=new_last/100;
new_last%=100;
int new_jiao=new_last/10;
int new_fen=new_last/10;
return RMB(new_yuan,new_jiao,new_fen);
}
//前++重载
RMB &operator--()
{
//从最小单位开始减
if(fen>0)
{
fen--;
}
else
{
if(jiao>0)
{
jiao--;
fen =9;
}
else
{
if(yuan>0)
{
yuan--;
jiao =9;
fen =9;
}
else
{
cout << "余额不足" <<endl;
}
}
}
return*this;
}
//后++重载
const RMB operator--(int)
{
RMB temp(*this);
--(*this);
return temp;
}
void display()
{
cout << yuan << "" <<jiao << "" << fen <<endl;
}
void show_count()
{
cout << "count= " << count << endl;
}
};
int RMB::count =0; //个数初始化为0
int main()
{
RMB r1(6,6,6);
RMB r2(2,2,2);
RMB r3=r1+r2;
r3.display();
cout << "====================" <<endl;
RMB r4=r1-r2;
r4.display();
cout <<"=======================" <<endl;
r3.show_count();
r4.show_count();
return 0;
}
RMB::有参构造 RMB::有参构造 RMB::有参构造 888 ==================== RMB::有参构造 444 ======================= count= 4 count= 4
这篇关于day5 C++的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!