学校的作业:写一个Money类。
//
// Created by 74706 on 2021/6/2.
//
#include<iostream>
using namespace std;
class Money
{
public:
int yuan, jiao, fen;
//构造函数
Money(int x=0, int y=0, int z=0);
//比较大小
friend Money operator>(Money &a, Money &b);//友元运算符重载函数,形参是a,b的引用
//实现相减
friend Money operator-(Money &a, Money &b);//友元运算符重载函数,形参是a,b的引用
};
Money::Money(int x, int y, int z){
yuan = x;
jiao = y;
fen = z;
}
//函数的实现
Money operator>(Money &a, Money &b)
{
if (a.yuan > b.yuan)
{
return a;
}
else if(a.yuan == b.yuan)
{
if (a.jiao > b.jiao)
{
return a;
}
else if (a.jiao == b.jiao)
{
if(a.fen>=b.fen)
{
return a;
}
else
{
return b;
}
}
else if (a.jiao < b.jiao)
{
return b;
}
}
else if (a.yuan < b.yuan)
{
return b;
}
}
//函数的实现
Money operator-(Money &a, Money &b)
{
{
Money r;
r = a > b;
if (r.yuan==a.yuan && r.jiao==a.jiao && r.fen==a.fen)
{
r.yuan -= b.yuan;
r.jiao -= b.jiao;
r.fen -= b.fen;
}
else
{
r.yuan -= a.yuan;
r.jiao -= a.jiao;
r.fen -= a.fen;
}
return r;
}
}
//显示输出
void print(Money& a, Money& b)
{
Money c, d;
c = a > b;
d = a - b;
cout << c.yuan << "." << c.jiao << c.fen << endl;
cout << d.yuan << "." << d.jiao << d.fen << endl;
}
int main()
{
int a1,a2,a3,a4,a5,a6;
cin >> a1 >> a2 >> a3;
cin >> a4 >> a5 >> a6;
Money a(a1,a2,a3), b(a4,a5,a6);//调用构造函数
print(a, b);
return 0;
}
如有错误,欢迎指正。