返回ostream的函数

Function returning to ostream

本文关键字:函数 ostream 返回      更新时间:2023-10-16

我想知道是否有可能创建返回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);
}

我希望输出是:

(x,y) = (12,7)  

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

通常通过重载类的流插入操作符来实现,如下所示:

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;
}

用作:

Point p;
cout << p;

为什么不为你的类实现operator <<呢?

如果您只需要打印一种输出,只需在包含类中重写operator<<。但是,如果您需要根据不同的上下文中打印不同类型的输出,您可以尝试创建不同代理类的对象。

代理对象可以保存对Point的引用,并根据需要打印它(或它的一部分)。

我将代理对象设为Point的私有成员类,以限制它们的可见性。

EDIT删除示例—我没有注意到这是作业

除了Point代码之外,您还可以使用辅助函数(下面的display())作为重载的替代方法:

std::ostream& display(std::ostream &os,Point &p) const {
 os<< p.x << p.y ;
 return os;
}
int main() {
    Point p;
    display(std::cout,p);    
        // This will call the display function and 
        // display the values of x and y on screen.
} //main

如果display函数需要访问私有成员,可以将其作为Point类的friend