jeudi 31 août 2017

In C++, why do I get different results using or not reference as result value?

class point
{
private:
double x,y;
public:
point(double x=0.0, double y=0.0)
{
    this->x=x;
    this->y=y;
}
point operator++()
{
    this->x=this->x+1.0;
    this->y=this->y+1.0;
    return *this;
}

point& operator++(int)
{
    point p=point(this->x, this->y);
    ++(*this);
    return p;

}

ostream& operator<< (ostream& o)
{
    o << "X: " << this->x << endl << "Y: " << this->y;
    return o;
}

friend ostream& operator<< (ostream& o,point p)
{
    o << "X: " << p.x << endl << "Y: " << p.y;
    return o;
}
};


int main() {
  point p=point();
  p++ << cout << endl; // first output
  cout << p++ << endl;// second output
}

I don't understand why the first output is incorrect (X: 6.95333e-310 Y: 6.95322e-310), while the second one is correct (X: 1 Y: 1).

And why this problem is solved by removing & at the end of the return value of the post-increment operator?

Aucun commentaire:

Enregistrer un commentaire