Return 构造的值 class

Return value from constructed class

我正在尝试模仿 stl classes 的 class 模板。我正在试验一种货币 class 作为一种新类型,以更好地处理我们系统中的货币。

这是我实验的粗略草稿:

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;
        }

};

我希望能够将此 class 实现为如下类型:

typedef CURRENCY<double> money;

int main()
{

    money m = 3.141592653589;

    m = m + 30;  // added assignment operator here

    cout << m << endl;

    return 0;

}

我想我什至不确定如何表达我所描述的内容,除了我想要 return 我的对象的当前 "value" 知道该对象并不是真的 一个值。我不确定如何让我的 class 携带可以 returned 和操作的默认表示值。

在这种情况下,我想 cout << m << endl; 到 return 我的 "new" 值:33.1416.

任何方向都会有所帮助,因为我只是想围绕这个概念进行思考。 注意:这段代码非常不完整,因为我正在试验,所以并不打算完全发挥作用,但请随时纠正任何逻辑问题或我前进的方向

我是个笨蛋,没有包括上面的作业...

首先,+ 和类似的运算符实际上并没有修改操作中涉及的对象,这意味着您必须创建一个新对象,然后 return 从运算符函数.

类似

CURRENCY operator+(T value)
{
    CURRENCY temp(*this);

    temp.p_iDollars += value;

    return temp;
}
template<typename T>
ostream& operator<<(ostream& lhs, const CURRENCY<T>& rhs) {
  lhs << /*output rhs the way you want here*/;
}

另外让operator+, operator/等修改调用对象也是很糟糕的设计。这些不应该是成员函数,也不应该修改调用对象。而是创建传递的 CURRENCY 的副本,修改它,然后 return 它。