如何在以下函数中不返回任何值?
bool operator<=(string a, const Zoo& z) {
// Pre: none
// Post: returns true if animal a is in Zoo z.
// the owner does not count as an animal.
for ( int i=0; i< z.count; i++ ) {
if (z.cage[i] == a){
return true;
}
else {
return false;
}
}
}
您的函数返回a,bool
但是有一个潜在的代码路径(例如z.count
is 0
),在该路径中,它可能到达函数的末尾并且不返回任何内容。因此,由编译器发出警告。
添加return false;
(或return true;
,但false
似乎是适当与您当前的逻辑)在你的函数结束。
正如其他人所指出的那样,您的else
立场也是错误的。我将其重写为:
bool operator<=(string a, const Zoo& z) {
// Pre: none
// Post: returns true if animal a is in Zoo z.
// the owner does not count as an animal.
for ( int i=0; i< z.count; i++ ) {
if (z.cage[i] == a){
return true;
}
}
return false;
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句