我一直在研究運算子多載的示例,有些將包括代碼片段,例如
ostream& operator<<(ostream& os, const Date& dt)
{
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
在ostream& operator<<(ostream& os, ...)似乎放置,什么ATLEAST似乎“隨機”圍繞一個C 程式。我的問題是,它可以放在任何地方嗎?C 如何查找、編譯和現在解釋<<類的多載Date以現在回傳 aostream&并使用此函式。
uj5u.com熱心網友回復:
您可以像以前一樣簡單地定義為行內
std::ostream& operator << ( ostream& os, const Date& dt ) {
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
但是在使用之前必須包含這個頭檔案,否則C 編譯器不會知道。
或者,您可以在類中定義行內好友,這將允許您訪問私有和受保護欄位,例如,如果“mo”、“da”和“yr”欄位在 Date 中是私有的。
class Date {
...
friend inline std::ostream& operator << ( ostream& os, const Date& dt ) {
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
};
或者您可以在標題(Date.h)中定義
class Date {
...
friend std::ostream& operator << ( ostream& os, const Date& dt );
};
然后在body(Date.cpp)檔案中實作
std::ostream& operator << ( ostream& os, const Date& dt ) {
os << dt.mo << '/' << dt.da << '/' << dt.yr;
return os;
}
uj5u.com熱心網友回復:
一個非常排序的答案可能是范圍中的operator函式定義的地方,這將是有效的。
如何控制范圍的函式/方法這個問題的范圍了。(雙關語)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/373602.html
標籤:C
