[英]ostream<<Iterator, C++
我正在嘗試構建一個打印列表的運算符,
為什么不會ostream << *它編譯?
void operator<<(ostream& os, list<class T> &lst)
{
list<T>::iterator it;
for(it = lst.begin(); it!=lst.end(); it++)
{
os<<*it<<endl; //This row
}
}
因為*it
沒有實現流插入。 也就是說, operator<<
沒有超載,它帶有ostream
和T
請注意,您應該返回ostream& os
以允許操作員鏈接。 您的函數模板定義也看起來不對。 考慮這樣做:
template< typename T >
ostream& operator<<(ostream& os, list<T> const& lst)
{
std::copy(
lst.begin(), lst.end()
, std::ostream_iterator< T >( os )
);
return os;
}
或者更好的是,支持所有元素和特征的流:
template< typename Elem, typename Traits, typename T >
std::basic_ostream< Elem, Traits >& operator<<(
std::basic_ostream< Elem, Traits >& os
, std::list<T> const& lst
)
{
std::copy(
lst.begin(), lst.end()
, std::ostream_iterator< T >( os )
);
return os;
}
Adittionaly,您可以將分隔符傳遞給std::ostream_iterator
構造函數,以便在每個元素之間插入。
*更新:*我剛剛注意到即使你的函數模板聲明是正確的,你也會處理一個依賴類型。 迭代器依賴於類型T
,因此您需要告訴編譯器:
typename list<T>::iterator it;
我認為問題出在你的模板聲明中。 以下應編譯並正常工作:
template <typename T>
void operator<<(ostream& os, list<typename T> &lst)
{
list<T>::iterator it;
for(it = lst.begin(); it!=lst.end(); it++)
{
os<<*it<<endl;
}
}
當然,這提供了列表的元素類型實際上可以與ostream
的<<
運算符一起使用。
您正在以錯誤的方式使用模板語法:
template<class T>
void operator<<(ostream& os, list<T> &lst)
{
list<T>::iterator it;
for(it = lst.begin(); it!=lst.end(); it++)
{
os<<*it<<endl; //This row
}
}
順便說一下,你應該返回對流的引用以允許鏈接輸出操作符,列表應該是const,你也可以使用標准庫來執行輸出循環:
template<class T>
std::ostream& operator<<(std::ostream& os, const std::list<T> &lst)
{
std::copy(lst.begin(), lst.end(), std::ostream_iterator<T>(os, "\n"));
return os;
}
重寫為:
template<class T>
ostream& operator<<(ostream& os, list<T>& lst){
typename list<T>::iterator it;
for(it = lst.begin(); it != lst.end(); ++it){
os << *it << endl;
}
return os;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.