文件Currency.h:
#ifndef CURRENCY_H
#define CURRENCY_H
enum signType{plus, minus};
class Currency{
public:
//构造函数,创建一个Currency类对象
Currency(signType theSign = plus,
unsigned long theDollars = 0,
unsigned int theCents = 0);
//析构函数
~Currency() {}
//给私有数据成员赋值
void setValue(signType, unsigned long, unsigned int);
void setValue(double);
//获取成员变量
signType getSign() const { return sign;}
unsigned long getDollars() const { return dollars; }
unsigned int getCents() const { return cents; }
//两个对象相加
Currency add(const Currency&) const;
//增加成员的值
Currency& increment(const Currency&);
//输出对象的值
void output() const;
private:
signType sign; //对象的符号
unsigned long dollars; //美元的数量
unsigned int cents; //美分的数量
};
Currency::Currency(signType theSign,unsigned long theDollars,unsigned int theCents)
{
setValue(theSign, theDollars,theCents);
}
void Currency::setValue(signType theSign, unsigned long theDollars, unsigned int theCents)
{
if(theCents>99){
throw "Cents should be < 100";
}
sign = theSign;
dollars = theDollars;
cents = theCents;
}
void Currency::setValue(double theAmount)
{
if(theAmount<0){
sign = minus;
theAmount=-theAmount;
}
else{
sign = plus;
}
dollars = (unsigned long) theAmount;
cents = (unsigned int)((theAmount+0.001-dollars)*100);
}
Currency Currency::add(const Currency& x) const
{
long a1,a2,a3;
Currency result;
a1 = dollars*100+cents;
if(sign==minus) a1=-a1;
a2=x.dollars*100+x.cents;
if(x.sign==minus) a2=-a2;
a3=a1+a2;
if(a3<0){
result.sign=minus;
a3=-a3;
}else{
result.sign=plus;
}
result.dollars=a3/100;
result.cents=a3-result.dollars*100;
return result;
}
Currency& Currency::increment(const Currency& x)
{
*this = add(x);
return *this;
}
void Currency::output() const
{
if(sign==minus){
std::cout<<"-";
}
std::cout<<'$'<<dollars<<".";
if(cents<10){
std::cout<<"0";
}
std::cout<<cents;
}
#endif // CURRENCY_H
文件main.cpp:
#include <iostream>
#include "Currency.h"
int main()
{
try{
Currency g,h(plus,3,50),i,j;
//使用两种形式的setValue来赋值
g.setValue(minus,2,25);
i.setValue(-6.45);
//调用成员函数add和output
j=h.add(g);
h.output();
std::cout<<"+";
g.output();
std::cout<<"=";
j.output(); std::cout<<std::endl;
//连续调用两次成员函数add
j=i.add(g).add(h);
i.output();
std::cout<<"+";
h.output();
std::cout<<"+";
g.output();
std::cout<<"=";
j.output(); std::cout<<std::endl;
//调用成员函数increment和add
i.output();
std::cout<<"+";
g.output();
std::cout<<"=";
j=i.increment(g).add(h);
i.output();
std::cout<<"+";
h.output();
std::cout<<"=";
j.output(); std::cout<<std::endl;
}
catch(char* e){
std::cout<<e<<std::endl;
}
return 0;
}