curr1.h
#ifndef Currency_
#define Currency_
#include <iostream>
#include <stdlib.h>
using namespace std;
enum sign {plus, minus};
class Currency {
// public 部分用于定义一些函数
public:
//constructor 创建一个给定类型的对象,他不可以有返回值,
Currency(sign s = plus, unsigned long d = 0,
unsigned int c = 0);
// destructor 当一个Currency对象超出作用域时将自动调用析构函数,不可以有返回值
~Currency() {}
bool Set(sign s, unsigned long d,
unsigned int c);
bool Set(float a);
sign Sign() const {return sgn;}
unsigned long Dollars() const {return dollars;}
unsigned int Cents() const {return cents;}
Currency Add(const Currency& x) const;
Currency& Increment(const Currency& x);
void Output() const;
// private部分用于定义一些函数和数据成员,这些函数和数据成员对于用户是不可见得
private:
sign sgn;
unsigned long dollars;
unsigned int cents;
};
// 在具体实现时,必须在每个函数名的前面加上Currency::,以指明该函数是Currency类的成员函数
Currency::Currency(sign s, unsigned long d,
unsigned int c)
{// Create a Currency object.
if (c > 99)
{// too many cents
cerr << "Cents should be < 100" << endl;
// 正常终止程序
exit(1);}
sgn = s; dollars = d; cents = c;
}
// 验证参数合法性
bool Currency::Set(sign s, unsigned long d,
unsigned int c)
{// Reset value.
if (c > 99) return false;
sgn = s; dollars = d; cents = c;
return true;
}
// 处理小数点后面的头两个数字
bool Currency::Set(float a)
{// Reset value.
if (a < 0) {sgn = minus; a = -a;}
else sgn = plus;
dollars = a; // extract integer part
// get two decimal digits
cents = (a + 0.001 - dollars) * 100;
return true;
}
Currency Currency::Add(const Currency& x) const
{// Add x and *this.
long a1, a2, a3;
Currency ans;
// convert invoking object to signed integers
a1 = dollars * 100 + cents;
if (sgn == minus) a1 = -a1;
// convert x to signed integer
a2 = x.dollars * 100 + x.cents;
if (x.sgn == minus) a2 = -a2;
a3 = a1 + a2;
// convert to currency representation
if (a3 < 0) {ans.sgn = minus; a3 = -a3;}
else ans.sgn = plus;
ans.dollars = a3 / 100;
ans.cents = a3 - ans.dollars * 100;
return ans;
}
/*
利用成员函数来设置数据成员的值可以确保数据成员拥有合法的值,如果数据成员被声明为public,还是在处理任务之前就要验证数据的合法性
*/
Currency& Currency::Increment(const Currency& x)
{// Increment by x.
*this = Add(x);
return *this;
}
void Currency::Output() const
{// Output currency value.
if (sgn == minus) cout << '-';
cout << '$' << dollars << '.';
if (cents < 10) cout << "0";
cout << cents;
}
#endif
curr1.cpp
// test currency class 我们一般把类的定义和类的实现分放在不同的文件中
#include <iostream>
#include <string>
#include "curr1.h"
using namespace std;
void main(void)
{
Currency g, h(plus, 3, 50), i, j;
g.Set(minus, 2, 25);
i.Set(-6.45);
j = h.Add(g);
j.Output(); cout << endl;
i.Increment(h);
i.Output(); cout << endl;
j = i.Add(g).Add(h);
j.Output(); cout << endl;
j = i.Increment(g).Add(h);
j.Output(); cout << endl;
i.Output(); cout << endl;
}