![](/img/trans.png)
[英]is it possible to override the c++ operator<< for a struct in a header file?
[英]Override binary << operator on struct
我試圖對像這樣的簡單結構進行覆蓋:
struct Node {
int data1;
int data2;
ostream& operator<<(ostream &o, const Node &n)
{
o << "(a: " << data1 << ", b: " << data2 << ")";
return o;
}
};
即時通訊:錯誤C2804:“運算符<<”參數過多
因此,如果我刪除第二個參數:
ostream& operator<<(ostream &o)
然后我得到:錯誤:二進制'<<':未找到采用'const Node'類型的右側操作數的運算符
這是怎么回事?
std::ostream& operator<<(std::ostream&, ...)
必須是自由函數。
將其移到課堂外,它將起作用。
之所以如此,是因為在類內部定義operator<<(std::ostream&)
(或其他二進制運算符)意味着該對象是LHS操作數。 您將不得不像這樣瘋狂寫:
Node << std::cout;
operator<<
需要兩個操作數。 有兩種方法可以在兩種類型之間定義operator<<
重載函數。
作為成員函數。 這就是operator<<
在std::basic_ostream
與一些基本類型之間的重載定義的方式。 當您使用std:cout << 10;
,它將解析為重載運算符std::basic_ostream<char>::operator<<(int)
當您將其定義為成員函數時,運算符的LHS是該類的實例。 運算符的RHS是該函數的參數。 這就是為什么當您將其定義為成員函數時,它只能有一個參數。
作為免費功能。 這就是在std::basic_ostream
和自定義類型之間定義operator<<
重載的方式。 這些函數必須有兩個參數。 第一個參數是運營商的LHS,第二個參數是運營商的RHS。
因此,您必須將std::ostream
與您的類之間的operator<<
重載定義為自由函數,其中std::ostream&
為第一個參數類型,而Node const&
為第二個參數類型。
std::ostream& operator<<(std:ostream& os, Node const& node);
在這樣的時候,我希望標准庫實現了一個功能:
template <typename T>
std::ostream& operator<<(std::ostream& os, T const& t)
{
return t.serialize(os);
}
然后,任何類都可以提供該功能
std::ostream& serialize(std::ostream& os) const;
並准備好與std::ostream
所有基本類型一樣使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.