C++ 问题重载运算符 - 类分配

标签 c++ operator-overloading

我在 stackoverflow 上查看了多个主题,但我对此类作业一无所获。我相信我正在使用书中介绍的代码,但我遇到了 = 运算符不复制和 - 运算符返回两个连接的值的问题。我希望你能帮助我理解并指出正确的方向。感谢您的帮助。

rectangleType 类有两个 protected 成员,长度和宽度,以及一个称为 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-=。同样,请咨询迈耶斯以获得更多解释。

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

关于C++ 问题重载运算符 - 类分配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22672513/

相关文章:

python - 是否可以在 Python 中重载对 vars(object) 的调用?

c++ - 重载运算符<<

c++ - CMake 和 VisualStudio : Group files in solution explorer

c++ - 如何设计一个最近最近使用的缓存?

c++ - 如何将 2 位从一个 int 复制到另一个?

C++ 指针动态数组和函数

c++ - 未定义引用。 DSO 缺失

c++ - 将复杂对象传递给 C++ 中的函数,但数组订阅运算符无法正常工作

c++ - Wandevoorde&Jossutis 书中带有两个参数的非友元运算符+

c++ - 将常规函数绑定(bind)到 std::function