[英]What is `std::ostream& (*f)(std::ostream &)` when overloading `<<` and why I would need it?
[英]When should I return std::ostream?
每當我要創建像std::string
運算符之類的運算符以顯示值(無運算符)時,我都會返回std::ostream
,但是我不知道為什么。 如果將std::ofstream
用作函數成員運算符function( std::cout
),我該如何返回它,何時應該執行它,為什么?
例:
class MyClass
{
int val;
std::ostream& operator<<(const std::ostream& os, const MyClass variable)
{
os << variable.val;
}
}
在std::string
:
std::string a("This is an example.");
std::cout << a;
過載<<
,通常會返回對ostream
的引用,以允許鏈接。 這個:
s << a << b;
相當於函數調用
operator<<(operator<<(s,a),b);
並且僅起作用,因為內部調用返回合適的類型作為外部調用的參數。
要實現此目的,只需按引用獲取stream參數,然后直接按引用返回相同的流:
std::ostream & operator<<(std::ostream & s, thing const & t) {
// stream something from `t` into `s`
return s;
}
或從其他重載返回:
std::ostream & operator<<(std::ostream & s, thing const & t) {
return s << t.whatever();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.