2010-09-14 160 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

相关问题