2010-09-14 164 views
4

嘿,我已經覆蓋operator<<,當我試圖打印方法(常量)我得到一個錯誤的使用方法:如何重載operator <<?

在被覆蓋的運營商:

ostream& operator <<(ostream& os, Date& toPrint) 
{ 
    return os << toPrint.GetDay() << "/" << toPrint.GetMonth() << "/" << toPrint.GetYear(); 
} 

在那裏我嘗試使用它:

void TreatmentHistory::TreatmentHistoryPrint() const 
{ 
    cout << m_treatmentDate << "\n" << endl; 
} 
+2

你會得到什麼錯誤? – SLaks 2010-09-14 23:43:58

+0

<< m_treatmentDate之前的紅線,當我踩着它時,錯誤是:沒有運算符「<<」匹配這個操作數。 – 2010-09-14 23:45:25

回答

8

您在const成員函數使用operator<<,從而m_treatmentDateconst(除非聲明mutable)。你需要修復您的operator<<採取const參數:

ostream& operator <<(ostream& os, const Date& toPrint); 

請注意,這個工作GetDay()GetMonth()GetYear()必須const成員函數,以及。

+0

完美,thanx。 – 2010-09-14 23:55:14

相關問題