内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
我通过设置不同字段的宽度来在C++上创建一个格式整洁的表。我可以用setw(N)做一些类似的事情
cout << setw(10) << x << setw(10) << y << endl;
或更改宽度
cout.width (10); cout << x; cout.width (10); cout << y << endl;
问题是,这两个选项都不允许我设置默认的最小宽度,而且每次向流写入内容时都必须更改它。
您可以创建一个重载的对象。operator<<
并包含一个iostream
对象,该对象将自动调用setw
内部。例如:
class formatted_output { private: int width; ostream& stream_obj; public: formatted_output(ostream& obj, int w): width(w), stream_obj(obj) {} template<typename T> formatted_output& operator<<(const T& output) { stream_obj << setw(width) << output; return *this; } formatted_output& operator<<(ostream& (*func)(ostream&)) { func(stream_obj); return *this; } };
您现在可以这样调用它:
formatted_output field_output(cout, 10); field_output << x << y << endl;