下面这个小程序是一个关于类的程序和运算符重载的方法
#include<iostream.h>
#include<stdlib.h>
enum sign{minus,plus};
class Money
{
friend ostream& operator<<(ostream& out,const Money& x);
private:
long amount;
public:
Money(sign s = plus, unsigned long d =0, unsigned long c =0);
~Money(){};
bool Set(sign s,unsigned long d,unsigned long c);
Money operator+ (const Money& x) const;
Money& operator+= (const Money& x)
{
amount +=x.amount ;
return *this;
}
};
Money::Money(sign s,unsigned long d,unsigned long c)
{
if(c>99)
{
cerr<<"分必须小于等于99"<<endl;
exit(1);
}
amount = d*100 + c;
if(s == minus) amount = -amount;
}
bool Money::Set(sign s,unsigned long d,unsigned long c)
{
if(c>99)
{
cerr<<"分必须小于等于99"<<endl;
exit(1);
}
amount = d*100 + c;
if(s == minus) amount = -amount;
return true;
}
Money Money::operator +(const Money& x) const
{
Money y;
y.amount =amount + x.amount ;
return y;
}
ostream& operator<<(ostream& out,const Money& x)
{
int temp = x.amount;
if(x.amount <0)
{
out<<'-';
temp = -temp;
}
long d = temp/100;
out<<'$'<<d<<'.';
int c = temp-d*100;
if(c<10) out<<'0';
out<<c;
return out;
}
void main()
{
Money g,h(plus,3,30),hg;
g.Set(minus,2,25);
hg=h + g;
g += h;
cout<<"h+g="<<hg<<endl;
cout<<"g="<<g<<endl;
}
输出:h+g = $1.05
g = $1.05