istream operator overloading c++

时光毁灭记忆、已成空白 提交于 2021-02-08 08:59:42

问题


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!

my code:

#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();
}

回答1:


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;    
}



回答2:


Actually the answer by Marc does not solve your problem completely. What is happenning is a bit more complicated:

You defined the function receiving a const &. That should have made the compiler simply refuse to compile your function. But here lies the problem: your constructor for date has default values for every parameter. Therefore, it can be called with only one parameter. Since it is not marked explicit, it works as an implicit conversion operator for an int (like date(i)). This means the compiler can interpret stream >> d.m_day as stream >> date(d.m_day). Your problem thus was: this is a call for operator>>(istream& stream, const date& d) and you get an infinite recursion.

Thus, you should not only make date& d non-const on your overload of operator>>, you should also mark the constructor explicit, like

explicit date(int day=1, int month=1, int year=2000)

so that it doesn't act as an implicit conversion operator. This should be done, actually, to almost every constructor that can possibly take only one parameter.



来源:https://stackoverflow.com/questions/16610586/istream-operator-overloading-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!