该代码主要处理的是货币类型。主要实现以下功能:
1、给成员赋值(下面的代码用2种方式实现)
2、确定成员值(符号、美元、美分)
3、实现2个对象相加(使用自己定义的函数)
4、输出
#include<iostream>
using namespace std;
enum signType{plus,minus}; //定义符号
class currency
{
public:
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) //用于赋值,上下2个函数主要是调用方式不一样
{
if(thecents>99)
cout<<"thecents should be <100"<<endl;
else
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); //提取小数部分,+0.001防止计算机有错误
}
currency currency::add(const currency &x)const
{
long a1,a2,a3; //a1,a2有啥区别??
currency result;
a1=dollars*100+cents; //调用对象转化为符号整数
if(sign==minus) a1=-a1;
a2=x.dollars*100+x.cents; //x转化位符号整数
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; //这个地方的*this自身调用很重要!!!
}
void currency::output()const
{
if(sign==minus)cout<<'-'; //输出调用对象的值
cout<<'$'<<dollars<<'.';
if(cents<10)cout<<'0';
cout<<cents;
}
int main()
{
currency g,h(plus,3,50),i,j,k;
double r;
//不同形式的赋值
g.setValue(minus,2,25);
i.setValue(-6.45);
j=h.add(g); //j为2中不同形式输入的结果
k=i.add(g).add(h);
k.output();
cout<<"\n";
h.output();
cout<<"+";
g.output();
cout<<"=";
j.output();
cout<<endl;
system("pause");
return 0;
}
第一点:类的第一个定义是与类名相同的函数,此函数称为构造函数,主要用来解决类中对象的初始化问题。
第二点,关于析构函数网上有很多讲解,如果自己函数不需要做什么特殊处理,带一个空函数即可。
第三点,关于定义的2个setValue()函数,主要是利用不同的输入得到相同的结果,现实工作中并不需要这样,比如对于第一个setValue(),主要针对a(plus,3,45)这样的输入。而第二个的setValue()函数主要是针对a(3.45)这样的输入,其实本人觉得第二种定义更加常用。
通过个人的理解,在类中申明了一个函数,就在后面给定义出来,防止出错,其次,需要什么函数就往类里面进行申明,这样防止忘记。其次关于private和public,公用成员可以直接在外面通过类名直接调用,而私有成员必须通过类名里面的构造函数间接调用,这点对于刚接触类来说,是非常重要的一点。
第四点,关于add函数,里面考虑到输入的不同情况,由于主函数中的i,j,k,g,h都是currency型的,并不能像正常情况下直接进行加减算法,应该定义函数。并且在这要考虑“引用调用对象的数据成员”和“引用参数对象x的数据成员”在语法上的区别。
第五点,关于各种函数的定义,按照自己思路来,考虑清楚各种情况,类的使用方法和大致结构就是这样。不过在工程比较大的情况,把主函数,头文件,定义全部分开处理更加清晰。