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

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

 #include
#include
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"<  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"<  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<<'$'< int c = temp-d*100;
 if(c<10) out<<'0';
 out< return out;
}

void main()
{
 Money g,h(plus,3,30),hg;
 g.Set(minus,2,25);
 hg=h + g;
 g += h;
 cout<<"h+g="< cout<<"g="<}

 

输出:h+g = $1.05

         g = $1.05

你可能感兴趣的:(数据结构+算法=程序)