嘿,我已经覆盖了operator<<
当我尝试在打印方法 (const) 中使用它时出现错误:
覆盖的运算符:
ostream& operator <<(ostream& os, Date& toPrint)
{
return os << toPrint.GetDay() << "/" << toPrint.GetMonth() << "/" << toPrint.GetYear();
}
我想在哪里使用它:
void TreatmentHistory::TreatmentHistoryPrint() const
{
cout << m_treatmentDate << "\n" << endl;
}
最佳答案
您正在使用您的 operator<<
在const
成员函数,因此 m_treatmentDate
是const
(除非声明 mutable
)。你需要修复你的 operator<<
采取const
参数:
ostream& operator <<(ostream& os, const Date& toPrint);
请注意,要使其正常工作 GetDay()
, GetMonth()
和 GetYear()
必须是 const
成员函数也是如此。
关于c++ - 如何覆盖运算符<<?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3713704/