簡體   English   中英

如何重載運算符+ =以添加兩個類對象

[英]How can I overload the operator += to add two class objects

我目前正在我的大學學習C ++課程。 目前,我們正在討論指針和重載運算符。 任務是關於英制長度單位(英尺和英寸)。

我想重載operator+= 我希望結果是這樣的:

d3 = d1 += d2; // d1, d2, d3 are class objects. Lets say d1(3, 4) and d2(1, 3). So the result should be d3(4, 7)

首先,有一個名為EnglishDistance的類(假定所有構造函數均已正確創建)

class EnglishDistance
{
private:
    int f, i;
public:
    EnglishDistance(int x, int y);
    EnglishDistance();

    // Do some other stuff
}

在該類中,除其他外,我已經實現了operator+的重載(可以正常運行):

EnglishDistance operator+(EnglishDistance d) {
        EnglishDistance temp;

        temp.f = f + d.f;
        temp.i = i + d.i;

        // Some checks (if inches are >= 12 I will subtract 12 inches and add 1 feet)

        return temp;
}

這就是到目前為止我對operator+=

EnglishDistance& operator+=(EnglishDistance& d) {

        *this += d

        // This is the check I was talking about. Only in this instance I am applying it on a pointer.
        while (this->i >= 12) {
            this->i -= 12;
            this->f++;
        }

        return *this;
}

當我嘗試運行此代碼時,我在Visual Studio上收到未處理的異常(堆棧溢出),因此顯然我搞砸了它。

有人可以指出我的代碼有什么問題嗎?

 *this += d

忽略這一行不會編譯(缺少分號)的事實,從邏輯上講也是毫無意義的。 在實現此操作的函數中,您將再次調用該操作!

這將導致無限的函數調用鏈,最終將堆棧粉碎成碎片,並導致程序崩潰。

實際上,您不僅需要重復說明如何使用該功能,還需要告訴計算機應該如何實現

我懷疑您的意思是:

this->f += d.f;
this->i += d.i;

(盡管可以省略this->

就像其他人所說的那樣,* this + = d調用EnglishDistance&operator + =(EnglishDistance&d),然后連續打* this + = d並依次調用EnglishDistance&operator + =,直到堆棧溢出為止。

到目前為止,您實際上在任何代碼中都根本不需要“ this”。 我認為這還是讓您感到困惑。 可以完全完全忽略它,而直接使用成員名稱即可。

另外,使用完整的有意義的名稱適當地命名您的成員。 您未來的同事將感謝您。

EnglishDistance & operator+=(EnglishDistance & rhs)
{
    // Convert to inches when adding
    m_inches += rhs.m_inches + rhs.m_feet * 12;

    // Now calculate the feet
    m_feet   += m_inches / 12;
    m_inches = m_inches % 12; // modulo operator gives remainder

    return *this;
}

暫無
暫無

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

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