【发布时间】:2016-03-18 17:19:22
【问题描述】:
我正在尝试使用模仿 stl 类的类模板进行猴子。我正在尝试将货币类作为一种新类型来更好地处理我们系统中的货币。
这是我的实验非常粗略的草稿:
template <class T> class CURRENCY
{
private:
int p_iDollars;
int p_iCents;
int p_iPrecision = pow(10, 5);
public:
CURRENCY(T dStartingValue)
{
int p = this->p_iPrecision;
double temp_dStartingValue = dStartingValue * p;
this->p_iDollars = temp_dStartingValue / p;
this->p_iCents = (dStartingValue - this->p_iDollars) * p;
}
CURRENCY operator+(T value)
{
this->p_iDollars = ((double) val()) + value;
}
CURRENCY operator-(T value)
{
this->p_iDollars = ((double) val()) - value;
}
CURRENCY operator*(T value)
{
this->p_iDollars = ((double) val()) * value;
}
CURRENCY operator/(T value)
{
this->p_iDollars = ((double) val()) / value;
}
CURRENCY operator= (int value)
{
this->p_iDollars = value;
}
double val()
{
return this->p_iDollars + ((double) this->p_iCents / this->p_iPrecision);
}
int dollars()
{
return this->p_iDollars;
}
int cents()
{
return this->p_iCents;
}
};
我希望能够将此类实现为如下类型:
typedef CURRENCY<double> money;
int main()
{
money m = 3.141592653589;
m = m + 30; // added assignment operator here
cout << m << endl;
return 0;
}
我想我什至不知道如何描述我所描述的内容,除了我想返回我的对象的当前“值”,因为我知道该对象并没有真正有价值。我不确定如何让我的类携带可以返回和操作的默认表示值。
在这种情况下,我希望 cout << m << endl; 返回我的“新”值:33.1416。
任何方向都会有所帮助,因为我只是想围绕这个概念来思考一下。 注意:这段代码非常不完整,因为我正在试验,所以并不打算完全发挥作用,但请随时纠正逻辑或我前进方向的任何问题
我是个笨蛋,没有包括上面的作业......
【问题讨论】:
标签: c++ class c++11 operator-overloading