简体   繁体   中英

How to override operator <<?

hey, i have overridden operator<< and when i'm trying to use it in a print method (const) i'm getting an error :

the overriden operator :

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

where i'm trying to use it :

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

You are using your operator<< in a const member function, thus m_treatmentDate is const (unless declared mutable ). You need to fix your operator<< to take const arguments:

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

Note that for this to work GetDay() , GetMonth() and GetYear() have to be const member functions as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM