簡體   English   中英

從構造的類返回值

[英]Return value from constructed class

我正在嘗試使用模仿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

任何方向都會有所幫助,因為我只是想繞過這個概念。 注意:這段代碼是超級完整的,並不是為了完全正常運行,因為我正在進行實驗,但請隨時糾正任何邏輯問題或我要去的方向

我是一個笨蛋,並沒有包括上面的任務......

首先, +和類似的運算符實際上並沒有修改操作中涉及的對象,這意味着您必須創建一個新的對象,然后從操作符函數返回。

就像是

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的副本,修改它並返回它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM