2010-02-12 24 views
5

如何使setw或类似的东西(boost格式?)与我的用户定义的ostream运算符一起工作? setw仅适用于推送到流中的下一个元素。使用setw与用户定义的ostream运算符

例如:

cout << " approx: " << setw(10) << myX; 

其中MYX是X型的,我有我自己的

ostream& operator<<(ostream& os, const X &g) { 
    return os << "(" << g.a() << ", " << g.b() << ")"; 
} 

回答

7

只是要确保所有的输出都作为与operator<<相同的呼叫的一部分发送到流。一个直接的方法来实现,这是使用辅助ostringstream对象:

#include <sstream> 

ostream& operator<<(ostream& os, const X & g) { 

    ostringstream oss; 
    oss << "(" << g.a() << ", " << g.b() << ")"; 
    return os << oss.str(); 
} 
1

也许像这样使用width功能:

ostream& operator<<(ostream& os, const X &g) { 
    int w = os.width(); 
    return os << "(" << setw(w) << g.a() << ", " << setw(w) << g.b() << ")"; 
} 
+0

这种方式,总宽度为3倍w和存在个别项目之间太多的空白。 – Manuel 2010-02-12 07:39:25

+0

用os.width()你应该可以自己修复它。 – shoosh 2010-02-12 23:15:55