c++ - 如何覆盖运算符<<?

标签 c++ operators operator-overloading

嘿,我已经覆盖了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_treatmentDateconst (除非声明 mutable )。你需要修复你的 operator<<采取const参数:

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

请注意,要使其正常工作 GetDay() , GetMonth()GetYear()必须是 const成员函数也是如此。

关于c++ - 如何覆盖运算符<<?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3713704/

相关文章:

java - 带有数学运算符的字符串到整数

c++ - 如何在 C++ 中重载赋值运算符?

c++ - 在 C++ 程序中包含 C 头文件

c++ - 无法部署 GLFW 3.2

c++ - 如何停止在所有桌面上显示 C/C++ WINAPI 窗口?

c++ - 将这些模板转换为别名声明

c - 指针上多个增量运算符的求值顺序

PostgreSQL 错误 : operator >> is not a valid ordering operator

c++ - 运算符重载中的类数据封装(私有(private)数据)

c++ - Set() 和 Get() 的重载括号运算符