我猜这是比实际更假设的,但我想知道是否可以使用switch语句在'assert'中返回'true'或'false'。 我意识到有更好的方法来做到这一点,但我想从错误处理的角度看待这个问题,而不是清理用户输入。在“assert”中使用switch语句(C++)
例如,考虑使用输入设置日期的Date类。在该类的SetDate()成员函数中,我想提出一个'assert'来处理由于输入引起的错误,例如月份为“13”,或月份为“2”(2月)为30天。这将是微不足道写一个switch语句,这是否:
switch(nMonth){
case 1:
case 3:(etc)
if(nDay>=1 && nDay <=31)
return true;
else
return false;
(etc)
default:
return false;
}
假设switch语句作为工作需要,我需要什么做的,使其在“断言”错误处理方案的工作?我按原样试过,但(并不奇怪)它没有编译。
编辑: @余浩: 这就是我如何修复它。我使用了一个bool函数。
bool TestDate(int nMonth, int nDay, int nYear){
switch(nMonth){
case 1:
case 3:
case 5:
case 7:
case 8:
case 10:
case 12:
if(nDay >=1 && nDay <=31)
return true;
break;
case 4:
case 6:
case 9:
case 11:
if(nDay >=1 && nDay <=30)
return true;
break;
case 2:
if((nYear % 400 == 0) || ((nYear % 100 !=0) &&(nYear % 4 == 0))){
if(nDay >=1 && nDay <=29)
return true;}
else if(nDay >=1 && nDay <=28)
return true;
else
return false;
break;
default:
return false;
}
return 0;
}
Date(int nMonth = 1, int nDay = 1, int nYear = 1970){
assert(TestDate(nMonth,nDay,nYear));
m_nMonth = nMonth;
m_nDay = nDay;
m_nYear = nYear;
}
你*可以*把它放在拉姆达,但我看不到点。 – chris
'TestDate()'中的'switch'语句相当丑陋 - 如果测试不符合,所有情况都会通过,但它恰好工作,因为如果任何早期测试失败,后续测试也会失败。也许它是这样设计的,但它似乎是一个幸运的事故。 –
@Michael:我在适当的位置放入了“break”语句,但是gcc编译器发出了一个警告:“控制到达非void函数的末尾”。当“break”语句被省略时,我没有收到任何警告。 – Huaidan