【发布时间】:2014-03-26 20:37:01
【问题描述】:
我在 stackoverflow 上查看了多个主题,但我对这个课程作业没有任何收获。我相信我正在使用书中介绍的代码,但是我遇到了 = 运算符不复制和 - 运算符返回两个连接的值的问题。我希望你能帮助我理解并指出我正确的方向。任何帮助表示赞赏。
rectangleType 类有两个受保护的成员,length 和 width,以及一个将它们相乘的名为 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
看起来 = 运算符中没有进行赋值,它返回第一个对象的长度和宽度而没有变化。此外, - 运算符似乎正在做它的工作,但分别返回长度和宽度,我不知道如何让它返回该区域。我在代码中尝试的一切都失败了。
+ 运算符添加并返回单独的长度和宽度值。看起来它确实正确地添加了它们。
您有什么方法可以帮助我了解如何解决这个问题?
【问题讨论】:
-
查看
operator=的实现,您并没有更改“接收”端的对象,而是更改并返回一个临时对象。这是不正确的。 (另外,operator=不应该是const,因为本质上会改变对象!)。 -
是的,我开始使用 temp 因为我无法让 length = rectangle.length 和 width = rectangle.width 工作。惊人的!我通过删除 const、删除 temp 并返回 *this!谢谢!
-
“不工作”是什么意思?
-
它不会分配值,但现在可以。现在,我只需要弄清楚如何让它返回区域而不是单独的长度和宽度。 :-)
-
不要在一个函数中使用两次
endl。这意味着'\n'然后是std::flush,所以只需将'\n'放在不需要刷新输出的地方。