函数返回 ostream

mbe*_*bes 2 c++ function stream

我想知道是否有可能创建返回 ostream 某些部分的函数,例如:

#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);
}
Run Code Online (Sandbox Code Playgroud)

我希望输出是:

(x,y) = (12,7)  
Run Code Online (Sandbox Code Playgroud)

我不希望 getXY() 返回任何字符串或字符数组。我可以以某种方式返回流的一部分吗?

Cha*_*had 5

通常这是通过为您的类重载流插入运算符来完成的,如下所示:

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;
}
Run Code Online (Sandbox Code Playgroud)

用作:

Point p;
cout << p;
Run Code Online (Sandbox Code Playgroud)