我正在尝试在 C++ 中为 Date 类重载 >> 运算符,但是当运行进入第一个 if 语句时,它会进入无限循环,你能帮帮我吗?
//operator
istream& operator >>(istream& is,CustomDate& d){
int day,month,year;
char ch1,ch2;
string test;
is>>skipws>>day>>ch1>>month>>ch2>>year;
if(!is){
is.clear(ios_base::failbit);
return is;
}
if(ch1!='/' || ch2!='/')
error("invalid date input");
d = CustomDate(day,month,year);
return is;
}
这是调用它的函数
CustomDate Menu::inputDate(){
CustomDate date;
cout<<"Input your departure date"<<endl;
cin>>date;
if(!cin){
error("invalid date format");
}
return date;
}
这是调用函数的循环
do{
try{
date = inputDate();
validDate = true;
}
catch(runtime_error& e){
cout<<"Date format not valid! must input as dd/mm/yyyy!"<<endl;
validDate = false;
}
}while(!validDate);
//customdate constructor
CustomDate::CustomDate()
:day(1),month(1),year(2012){}
CustomDate::CustomDate(int day, int month, int year)
:day(day),month(month),year(year){
if(day<0 || day>30)
error("Error: Date constructor");
if(month<0 || month>12)
error("Error: Date constructor");
if(year<0)
error("Error: Date constructor");
}