Question

This is my complete code everything is working just fine except the << overloading. Can anyone tell me why is it producing an error while >> is working fine any kind of help will be appreciated thanks.

error " see the declaration of << "

#include<iostream>
#include<conio.h>
using namespace std;
class point
{
private:
    int x,y;
public:
point(int x=0, int y=0)
{
    this->x = x;
    this->y = y;
}
point & operator + (const point &obj)
{
    point temp;
    temp.x = this->x + obj.x;
    temp.y = this->y + obj.y;
    return temp;
}
point & operator - (const point &obj)
{
    point temp;
    temp.x = this->x - obj.x;
    temp.y = this->y - obj.y;
    return temp;
}
friend point & operator >>(istream in, point obj);
friend point & operator <<(ostream out, point obj);
};
void main()
{
    _getch();
}
point & ::operator >> (istream in, point obj)
{
    in >> obj.x;
    in >> obj.y;
    return obj;
}
point & ::operator << (istream out, point obj)    // <--- Here is the Problem
{
    //out << "( " << obj.x << " , " << obj.y << " )";
    return obj;
}
Was it helpful?

Solution

You should always return the stream reference, not the point reference.

Update: I think someone else pointed out the actual problem in the comments (istream instead of ostream). Also, you are passing the streams by value instead of by reference. Here is what your code should look like:

istream& ::operator >> (istream &in, const point &obj)
{
    in >> obj.x;
    in >> obj.y;
    return in;
}
ostream& ::operator << (ostream &out, const point &obj)    // <--- Here is the Problem
{
    out << "( " << obj.x << " , " << obj.y << " )";
    return out;
}

Update to my update: I would also say that the point value should be passed as a const reference otherwise you would never be able to pass in a constant point value (assuming you would ever want to). See my above edits.

Yet another point (not really relevant): Try not to make them friends of Point unless you have to. It would seem that the x and y values would need to be publicly accessible at some point. If they publicly accessible, then there is no reason for the operators to be friends.

OTHER TIPS

The function was declared as taking an ostream, but defined as taking an istream. That's the error.

However, there are a couple of issues here.

  • You should take the stream objects by reference, otherwise you're working with a copy, and they might not even by copyable.
  • You should return a reference to the stream object to allow chaining operators.

The recommended overloads take this form:

ostream& operator<<(ostream& os, const point& p)
{
    os << "(" << p.x << "," << p.y << ")";
    return os;
}

You can now do stuff like the following:

point x;
point y;

// ...

std::cout << x << " and " << y << "\n";
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top