我如何在以下函数中不返回任何值?
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;
}
}
}
最佳答案
你的函数返回一个 bool
但有一个潜在的代码路径(例如 z.count
是 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;
}
关于c++ - 警告 : control may reach end of non-void function [-Wreturn-type],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26597713/