繁体   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