重载操作符的问题——类赋值
C++ Trouble Overloading Operators - Class Assignment
我已经在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;
}
- 为"adjacent"变量赋值时出现问题
- 关于 c++ 函数中指针赋值的简单问题
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- C++:关于使用 Stroustrup 示例移动构造函数/赋值的问题
- c++问题:给一个变量赋值后,另一个变量发生了变化
- 复制和赋值构造函数的问题
- 类模板的用户定义赋值运算符时遇到问题
- template_back和move赋值构造函数存在问题
- 赋值重载:为什么使用相同的对象会导致程序中出现问题
- C++赋值重载自赋值问题
- 重载赋值运算符的问题
- 交换与使用std::map[]运算符赋值(const问题)
- C++中赋值运算符和 c 字符串的问题
- 在C++中重载赋值运算符时出现问题
- 我在 c++ 中的赋值重载运算符有什么问题?(包括详细信息)
- C++ 向量构造函数和赋值问题
- "无符号长整型"和'unsigned long long int'赋值问题
- 动态分配结构数组:赋值问题(c++)
- c++ OOP初学者,赋值问题
- 奇怪的赋值问题-C++