【发布时间】: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 和重载运算符