#include<iostream>
#include<string>
using namespace std;
//因为用户仅仅通过公有部分的接口与currency类进行交互,所以对私有部分的修改不会影响应用程序的正确性
enum signType{plus1,minus1};//使用{plus,minus}报错应该是与原本库中的混用了,改成{plus1,minus1}
class currency{
public:
//构造函数,公有部分的第一个成员函数与类名相同,构造函数指明了创建一个类对象的方法,而且没有返回值,创建currency对象构造函数被自动调用
currency(signType theSign = plus1,
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 ){
//创建一个currency对象
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=minus1;theAmount=-theAmount;
}
else sign=plus1;
dollars=(unsigned long)theAmount;//提取整数部分
cents=(unsigned int)((theAmount-dollars+0.001)*100); //提取两位小数
}
currency currency::add(const currency&x)const{
//把x和*this相加
long a1,a2,a3;
currency result;
//把调用对象转换为符号整数
a1=dollars*100+cents;
if(sign==minus1)a1=-a1;
//把x转换为符号整数
a2=x.dollars*100+x.cents;
if(sign==minus1)a2=-a2;
a3=a1+a2;
//转成currency对象表达式
if(a3<0){result.sign=minus1;a3=-a3;}
else result.sign=plus1;
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==minus1)cout<<'-';
cout<<'$'<<dollars<<'.';
if(cents<10)cout<<'0';
cout<<cents;
}
调用以上的currency.h
#include<iostream>
#include"currency.h"
using namespace std;
int main(){
currency g,h(plus1,3,50),i,j;
//使用两种形式的setvalue来赋值
g.setValue(plus1, 2, 25);
i.setValue(-6.45);
//调用函数add和output
j=h.add(g);
h.output();
cout<<"+";
g.output();
cout<<"=";
j.output();cout<<endl;
//连续调用两次成员函数add
j=h.add(g).add(h);
//省略了输出语句
//调用成员函数increment和add
j=i.increment(g).add(h);
//省略了输出语句
//测试异常
cout<<"Attempting to initialize with cents = 152"<<endl;
try{i.setValue(plus1,3,152);}
catch(char const *e){
cout<<"Caught thrown exception"<<endl;
}
return 0;
}