【问题标题】:Function returning to ostream返回 ostream 的函数
【发布时间】:2011-10-21 20:52:47
【问题描述】:

我想知道是否有可能创建返回部分 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() 返回任何字符串或字符数组。我可以以某种方式返回部分流吗?

【问题讨论】:

  • 为什么不直接返回std::string
  • 很明显我可以这样做,但这是我大学 OOP 的“家庭作业”的一部分。我无法编辑行:std::cout
  • 你不能返回 std::ostream,它有一个私有的拷贝构造函数。对于 std::stringbuf 也是如此。不过,您可以做的是返回一个带有两个值的 std::pair 和重载运算符

标签: c++ function stream


【解决方案1】:

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

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;

【讨论】:

  • 你怎么不退ostream?
【解决方案2】:

为什么不为您的班级实施operator &lt;&lt;?它会做你想做的事。

【讨论】:

  • 这不是问题。我可以重载
  • 然后实现一堆只实现 I/O 的友元类,每个类都有自己的operator &lt;&lt;
【解决方案3】:

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

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

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

编辑删除了示例——我没有注意到这是家庭作业。

【讨论】:

  • +1,在给定的约束条件下,代理对象方法是最好的方法。
【解决方案4】:

除了您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-10
    • 2014-03-23
    • 1970-01-01
    • 1970-01-01
    • 2015-10-31
    相关资源
    最近更新 更多