tags:

views:

519

answers:

2

im required to write a function to overload the ==operator to compare width, height and colour. i need to return 'Y' if its equal and 'N' if its not.

this is my code which i think its correct but keeps getting the error in the title.

i've done searches and nothing came close to comparing 3 data as most examples are for comparing 2 datas.

#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;
}
+2  A: 

Looks like you need some parentheses:

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

It's an operator precedence issue; the << is being applied to rectB before the == runs.

Michael Myers
Sometimes I hate the random sorting.
Michael Myers
thanks. think i've just made myself stupider with this stupid qns.
RealiX
No, I'd say most people who work with C++ have done this at one time or another. What you can learn from this is that even when errors seem cryptic, they often have all the information you need. You could have looked at the message and wondered, "Why does the compiler think I'm trying to use an operator << with a Rectangle?" And that would have led you to the correct answer.
Michael Myers
the codes cout << "Are B and C equal? Ans: " << rectB==rectC << endl;are actually part and given in the qns, so im not really sure if adding the brackets are right. but since its working, i'm going to ask my lecturer abt it.
RealiX
Who downvoted both of the answers, and why?
Michael Myers
Funny how this answer is pretty much identical to mine, and was posted 2 seconds earlier, and yet didn't get voted up as much as mine. And yeah, why the down votes??
Fred Larson
@RealiX - so your instructor not only gives you an assignment to code up a broken `operator==()` but also gives you broken test/example use code? Yikes...
Michael Burr
+6  A: 

"<<" is higher precedence than "==". Put your comparison in parentheses:

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