【问题标题】:error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'Rectangle' (or there is no acceptable conversion)错误 C2679:二进制“<<”:未找到采用“矩形”类型右侧操作数的运算符(或没有可接受的转换)
【发布时间】: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++


【解决方案1】:

cout << "Are B and C equal? Ans: " << (rectB == rectC) << endl;

【讨论】:

    【解决方案2】:

    看起来你需要一些括号:

    cout << "Are B and C equal? Ans: " << (rectB==rectC) << endl;
    

    这是一个运算符优先级问题;在 == 运行之前,&lt;&lt; 被应用于 rectB

    【讨论】:

    • 有时我讨厌随机排序。
    • 谢谢。我想我只是用这个愚蠢的 qns 让自己变得更愚蠢。
    • 不,我想说大多数使用 C++ 的人都曾经这样做过。您可以从中学到的是,即使错误看起来很神秘,它们通常也包含您需要的所有信息。您可能已经查看了该消息并想知道,“为什么编译器认为我正在尝试将运算符
    • 代码 cout
    • @RealiX - 所以你的导师不仅给你一个任务来编写一个损坏的operator==(),而且还给你损坏的测试/示例使用代码?哎呀...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多