重载操作符的问题——类赋值

C++ Trouble Overloading Operators - Class Assignment

本文关键字:赋值 问题 操作符 重载      更新时间:2023-10-16

我已经在stackoverflow上查看了多个主题,并且我没有得到这个类作业的任何地方。我相信我正在使用的代码,因为它是在书中提出的,但我有问题=操作符不复制和-操作符返回两个值连接。我希望你能帮我理解,给我指出正确的方向。如有任何帮助,不胜感激。

rectangleType类有两个受保护的成员,长度和宽度,以及一个叫做rectangleType.area()的函数将它们相乘。在作业中,我应该改变书的代码,返回长度和宽度,而不是返回区域,但我不能让这些工作正确。(关系和流操作符工作正常)

从rectangleType.h:

rectangleType operator=(const rectangleType&) const; // replace one rectangle with another
rectangleType operator-(const rectangleType&) const; // subtract one rectangle from another
从rectangleTypeImp.cpp

rectangleType rectangleType::operator=(const rectangleType& rectangle) const
{
    rectangleType temp = *this;
    temp.length = rectangle.length;
    temp.width = rectangle.width;
    return temp;
}
rectangleType rectangleType::operator-(const rectangleType& rectangle) const
{
    rectangleType temp = *this;
    if(temp.length - rectangle.length >= 1 && temp.width - rectangle.width >= 1)
    {
        temp.length = temp.length - rectangle.length;
        temp.width = temp.width - rectangle.width;
        return temp;
    }
    else
    {
        cout << endl << "Dimensions are not large enough."
             << "Cancelling operation and returning dimensions"
             << "of left operand." << endl;
    }
    return temp;    
}
在主文件中,我创建了以下对象:
rectangleType myOtherYard(26, 19);
rectangleType myBrothersYard(2, 2);
rectangleType myMothersYard(3, 3);

并写了下面的代码:

myOtherYard = myBrothersYard;
cout << endl << "myOtherYard = myBrothersYard: " 
     << myOtherYard;
cout << endl << "myBrothersYard - myMothersYard: " 
     << myBrothersYard + myMothersYard;

下面是我得到的输出(使用格式化打印):

myOtherYard = myBrothersYard:   26.0019.00 
myBrothersYard - myMothersYard: 3.003.00

看起来在=操作符中没有进行赋值操作,它返回第一个对象的长度和宽度,没有改变。此外,-操作符似乎正在做它的工作,但分别返回长度和宽度,我不知道如何让它返回的面积。我在代码中所尝试的一切都失败了。

+操作符分别添加和返回长度和宽度值。它看起来是正确的。

你能告诉我如何解决这个问题吗?

首先,赋值操作应该返回对自己的引用。它也不应该是const,因为你是在给自己赋值。请参阅许多参考文献,主要是Scott Meyers的"Effective c++"。

因为你只是在学习,我没有看到它在那里,我认为你不应该知道关于移动语义,所以我将省略它…

另一个矩形的赋值操作符…

rectangleType &
rectangleType::
operator=(rectangleType const & that)
{
    length = that.length;
    width = that.width;
    return *this;
}

然而,看起来默认的赋值操作符就足够了。如果需要为类编写赋值操作符,我想您还必须编写复制构造函数。

如果你有一个operator-,你也应该有operator-=。同样,请向Meyers咨询更多的解释。

关于你的减法实现…天哪。真的吗?找出错误?然后返回一个不是正确答案的对象?

这样做可能会有帮助:

rectangleType& rectangleType::operator=(const rectangleType& rectangle) 
{
    if (this != &rectangle)
    {
         length = rectangle.length;
         width = rectangle.width;
    }
    return *this;
}