Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function returning to ostream

I wonder if there is any possibility to create function returning some part of ostream, like in example:

#include <iostream>

class Point {
  public:
    Point(int x, int y){
      this->x = x;
      this->y = y;
    }

    ?? getXY(){  // I wish this function returned ostream
        return ??;
    }
  private:
    int x,y;
};

int main() {
  Point P(12,7);
  std::cout << "(x,y) = " << P.getXY(); // (12, 7);
}

I wish the output was:

(x,y) = (12,7)  

I don't want getXY() to return any string or char array. May I somehow return part of stream?

like image 461
mbes Avatar asked Dec 07 '25 08:12

mbes


1 Answers

Generally this is done by overloading the stream insertion operator for your class, like this:

class Point {
  public:
    Point(int x, int y){
      this->x = x;
      this->y = y;
    }

    int getX() const {return x;}
    int getY() const {return y;}
  private:
    int x,y;
};

std::ostream& operator<<(std::ostream& out, const Point& p)
{
    out << "(x,y) =" << p.getX() << "," << p.getY();
    return out;
}

Used as:

Point p;
cout << p;
like image 80
Chad Avatar answered Dec 08 '25 23:12

Chad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!