istream 运算符重载 C++
问题描述:
我正在尝试做一个简单的 istream 运算符重载,但是由于某种原因,一旦进入这个函数,程序就会进入无限循环.请帮忙!
i'm trying to do a simple istream operator overloading, but for some reason, once entering this function, the program enters an infinite loop. please help!
我的代码:
#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).
This code seems wrong to me, since you are trying to modify a const
object (d).
istream& operator>> (istream& stream, const date& d){ //overload >>
stream >> d.m_day;
return stream;
}