[英]std::setw for the whole operator<< of user-defined type
我们知道,std :: setw()仅影响下一个输出。
因此,在表输出中对齐用户定义类型的整个operator <<的 标准实践是:
class A
{
int i, j;
public:
friend ostream& opeartor<<(ostream& out, const A& a) {
return << "Data: [" << i << ", " << j << "]";
}
}
// ...
A[] as;
out << std::left;
for (unsigned i = 0; i < n; ++i)
out << std::setw(4) << i
<< std::setw(20) << as[i] // !!!
<< std::setw(20) << some_strings[i]
<< some_other_classes[i] << std::endl;
out << std::right;
只需将setw()
方法添加到您的类中即可:
class A
{
int i, j;
mutable int width = -1;
public:
A& setw(int n) {
this->width = n;
return *this;
}
friend ostream& operator<<(ostream& out, const A& a);
};
在打印时,如果要对齐,只需使用它:
int main() {
A as[5];
for (auto & a : as)
cout << a.setw(15) << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.