c++ - istream 运算符重载 C++

标签 c++ operator-overloading

我正在尝试做一个简单的 istream 运算符重载,但由于某种原因,一旦进入这个函数,程序就会进入死循环。 请帮忙!

我的代码:

#include <iostream>
#include <string>
using namespace std;

 class date{

int m_day,m_month,m_year;

public:

date(int day=1,int month=1,int year=2000){    //constructor
    if (day>0 && day<32 && month>0 && month<13){
        m_day =day;
        m_month=month;
        m_year=year;
    }
}


friend ostream& operator<< (ostream& out, const date& d);
friend istream& operator>> (istream& in, const date& d);
};


istream& operator>> (istream& stream, const date& d){              //overload >>
stream >> d.m_day;
return stream;

}

void main(){  

date date1;

cin>>date1;                   //check istream

getchar();
}

最佳答案

这段代码对我来说似乎是错误的,因为您正在尝试修改 const 对象 (d)。

istream& operator>> (istream& stream, const date& d){              //overload >>
    stream >> d.m_day;
    return stream;    
}

关于c++ - istream 运算符重载 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16610586/

相关文章:

c++ - 运算符++ 中的 Int 参数

c++ - 对类实例和 vector 使用赋值运算符

c++ - 现在对临时工程的非 const 引用?

c++ - 运算符重载 : cannot add two pointers

python - 使用 pybind11 在多线程 C++ 程序中嵌入 Python 解释器

c++ - 使用不同文件声明函数/vector 的 C++ 中的多重定义错误

c++ - 在 IBM i 系列上为 std::map 使用自定义比较器

c++ - 重载重载运算符=?

c++ - 不匹配 ‘operator-’

c# - C# 中的运算符重载