C++ 警告:控件可能到达非无效功能的末尾[-Wreturn类型]
我如何在以下函数中不返回任何值C++ 警告:控件可能到达非无效功能的末尾[-Wreturn类型],c++,C++,我如何在以下函数中不返回任何值 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){
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操作符您的函数返回一个bool
,但存在一个潜在的代码路径(例如z.count
is0
),在该路径中,它可能到达函数的末尾,但不返回任何内容。因此,编译器发出了警告
添加返回false
(或返回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;
}
bool操作符您意外地将“notfound”case作为else分支放入循环体中。这意味着,如果第一个项目不是您要查找的项目,则您已经退出循环
这当然有两个问题:如果您正在寻找的元素位于另一个位置,那么您找不到它。另外,如果z.cage
为空,则不进入循环,也不返回任何值,这是编译器警告您的内容
通过删除else分支来解决问题。只有在循环之后,return false
从那时起,您就知道没有找到该元素。当z.count小于1时,您可以删除else部分,然后在循环外部返回false。这是运算符重载的一个非常糟糕的用法。警告意味着编译器无法证明控件从未到达结束}
。即使您碰巧知道z.cout>0
,也可能会收到警告。除了运算符的实现问题之外,使用