【问题标题】:Return value from constructed class构造类的返回值
【发布时间】: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 &lt;&lt; m &lt;&lt; endl; 返回我的“新”值:33.1416

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

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

【问题讨论】:

    标签: c++ class c++11 operator-overloading


    【解决方案1】:

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

    类似

    CURRENCY operator+(T value)
    {
        CURRENCY temp(*this);
    
        temp.p_iDollars += value;
    
        return temp;
    }
    

    【讨论】:

    • 这实际上消除了我阅读时的一些困惑,谢谢!
    • 更好的方法是将operator+=实现为成员函数并使operator+成为非成员,但在operator+中使用operator+=
    【解决方案2】:
    template<typename T>
    ostream& operator<<(ostream& lhs, const CURRENCY<T>& rhs) {
      lhs << /*output rhs the way you want here*/;
    }
    

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

    【讨论】:

      猜你喜欢
      • 2011-10-14
      • 2012-08-07
      • 2015-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-23
      • 1970-01-01
      相关资源
      最近更新 更多