c++ - 警告 : control may reach end of non-void function [-Wreturn-type]

标签 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){
            return true;
        }

        else {
          return false;
        } 
    }
}

最佳答案

你的函数返回一个 bool 但有一个潜在的代码路径(例如 z.count0)它可能到达函数并且什么都不返回。因此,编译器发出警告。

在函数末尾添加 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/

相关文章:

C++:比较不同大小的整数会导致 UB 吗?

c++ - 如何观察放卷不当?

c++ - 为什么使用 '\0' 而不是 memset 的 0?

c++ - 具有成对参数的模板函数

c++ - 拥有与标准 header 同名的自己的 header 是否是未定义的行为?

C++:将 L""string 分配给 WCHAR[]?

c++ - 图像每一行在 x 方向上的一维卷积

c++ - 使用随机数生成器为随机数生成器池播种

c++ - 使用 GL_DRAW_FRAMEBUFFER 目标时,glBindFramebuffer 会导致 "invalid operation"GL 错误

c++ - Windows SDK 7.1 编译器上的 yvals.h C4514 警告