类于内联函数,外联函数,运算符重载以及类对象的使用

下面这个小程序是一个关于类的程序和运算符重载的方法

 #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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值