警告:控件可能达到非无效功能的末尾[-转弯类型]
warning: control may reach end of non-void function [-Wreturn-type]
如何在以下函数中不返回任何值?
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;
}
您不小心将"not found"事例作为else分支放入循环体中。这意味着,如果第一个项目不是您要查找的项目,那么您已经退出了循环。
这当然有两个问题:如果你要查找的元素在另一个位置,你就找不到它。此外,如果z.cage
为空,你就不会进入循环,也不会返回任何值,这就是编译器告诉你的警告。
通过删除else分支来解决问题。只有循环之后的,return false
,从那时起你就知道元素还没有找到。
相关文章:
- ArduinoJson 6.15.2:JsonObject没有命名类型
- 防止主数据类型C++的隐式转换
- 大量序列中核苷酸类型的快速计数
- 如何从C++中的依赖类型中获得它所依赖的类型
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- 是否可以初始化不可复制类型的成员变量(或基类)
- 如何获取std::result_of函数的返回类型
- 从父命名空间重载类型
- 如果C++类在类方法中具有动态分配,但没有构造函数/析构函数或任何非静态成员,那么它仍然是POD类型吗
- 我想将一个对T类型的非常量左值引用绑定到一个T类型的临时值
- Openssl 1.1.1d无效使用不完整的类型"struct dsa_st"
- 访问者访问变体并返回不同类型时出错
- 在VS2010-VS2015下编译时,如何使用decltype作为较大类型表达式的LHS
- 处理小于cpu数据总线的数据类型.(c++转换为机器代码)
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 模板元程序查找相似的连续类型名称
- 是否可以从int转换为enum类类型
- 构造函数正在调用一个使用当前类类型的函数
- 我应该使用什么来代替void作为变体中的替代类型之一
- 警告:控件可能达到非无效功能的末尾[-转弯类型]