【发布时间】:2009-09-22 17:07:43
【问题描述】:
我需要编写一个函数来重载 == 运算符来比较宽度、高度和颜色。如果相等,我需要返回'Y',否则返回'N'。
这是我认为正确的代码,但一直给我错误:
错误 C2679:二进制“
我已经搜索了一个答案,但没有什么能接近比较 3 个数据,因为大多数示例都是比较 2 个数据。
#include <iostream>
#include <string>
using namespace std;
class Rectangle
{
private:
float width;
float height;
char colour;
public:
Rectangle()
{
width=2;
height=1;
colour='Y';
}
~Rectangle(){}
float getWidth() { return width; }
float getHeight() { return height; }
char getColour() { return colour; }
Rectangle(float newWidth, float newHeight, char newColour)
{
width = newWidth;
height = newHeight;
colour = newColour;
}
char operator== (const Rectangle& p1){
if ((width==p1.width) && (height==p1.height) && (colour==p1.colour))
return 'Y';
else
return 'N';
}
};
int main(int argc, char* argv[])
{
Rectangle rectA;
Rectangle rectB(1,2,'R');
Rectangle rectC(3,4,'B');
cout << "width and height of rectangle A is := " << rectA.getWidth() << ", " << rectA.getHeight() << endl;
cout << "Are B and C equal? Ans: " << rectB==rectC << endl;
return 0;
}
【问题讨论】:
-
我知道您的任务是让
operator==()返回“Y”或“N”。但是你应该告诉你的导师,这是一个非常糟糕、非常糟糕、非常糟糕的要求。它可能会让学生认为在现实生活中让operator==()像这样工作是可以的。然后,当他们尝试类似“if (rectB == rectC) { /* 不应该到达这里 */ }”之类的东西时,他们会得到一个不错的小惊喜。
标签: c++