函数返回ostream
我想知道是否有可能创建返回 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() 返回任何字符串或字符数组。我可以以某种方式返回部分流吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通常,这是通过重载类的流插入运算符来完成的,如下所示:
用作:
Generally this is done by overloading the stream insertion operator for your class, like this:
Used as:
为什么不直接为您的类实现
operator <<
呢?它会完全按照你的意愿去做。Why not just implement
operator <<
for your class? It would do exactly what you want.如果您只需要打印一种输出,只需在包含类中重写
operator<<
即可。但是,如果您需要根据不同的上下文打印不同类型的输出,您可以尝试创建不同代理类的对象。代理对象可以保存对 Point 的引用,并根据您的需要打印它(或其中的一部分)。
我会将代理对象设置为 Point 的私有成员类,以限制它们的可见性。
编辑删除了示例——我没有注意到这是家庭作业。
If you only need to print one sort of output, just override
operator<<
in your containing class. But, if you need to print different sorts of output according in different contexts, you might try creating objects of different proxy classes.The proxy object could hold a reference to
Point
, and print it (or portions of it) according to your needs.I would make the proxy objects private member classes of
Point
to restrict their visibility.EDIT Removed sample -- I didn't notice this was homework.
除了
Point
代码之外,您还可以使用辅助函数(下面的display()
)作为重载的替代方法:display
函数如果需要访问私有成员,可以将其设为类Point
的friend
。In addition to your
Point
code, you can use a helper function (below,display()
) as an alternative to overloading:The
display
function can be made afriend
of classPoint
if it needs to access private members.