2017-10-17 138 views
0

我們知道,std :: setw()隻影響下一個輸出。std :: setw整個運算符<<用戶自定義類型

所以,對準什麼標準的做法整個操作< <表輸出用戶定義類型的:

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; 

回答

0

只需添加一個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; 
} 
+0

他們打算怎麼樣?或者他們應該開始爲他們需要的每種格式修改這個'operator <<'?如果他們*需要不同的格式呢? – StoryTeller

+0

@StoryTeller,我改進了我的答案,以便它可以根據需求對班級進行格式化 –

相關問題