Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

istream operator overloading c++

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();
}
like image 975
user1887990 Avatar asked Feb 10 '26 12:02

user1887990


1 Answers

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;    
}
like image 155
Marc Claesen Avatar answered Feb 13 '26 05:02

Marc Claesen