c++ - 控制到达非空函数的结尾

标签 c++ qt return

以下代码片段在编译时会产生一些警告信息:

Cluster& Myclass::getCluster(const Point &p)
{
    foreach (Cluster c, *this)
        foreach (Point point, c)
            if (point == p)
                return c;
}

警告是:

  1. 返回对局部变量“c”的引用[默认启用]
  2. 控制到达非空函数的末尾[当使用-Wreturn-type时]

我知道如果条件失败我不会返回值。但是,当我尝试 return 0 时,它给了我错误。

我该如何解决这些问题?

最佳答案

如果您的函数无法找到匹配的 Cluster,那么您应该让它返回一个指针:

Cluster* Myclass::getCluster(const Point &p)
{
    foreach (Cluster c, *this)
        foreach (Point point, c)
            if (point == p)
                return &c;
    return 0; // or return nullptr; in C++11
}

但这还行不通,因为c 是一个局部变量。所以你把它作为一个引用,就像这样:

Cluster* Myclass::getCluster(const Point &p)
{
    foreach (Cluster& c, *this)
        foreach (Point point, c)
            if (point == p)
                return &c;
    return 0; // or "return nullptr;" in C++11
}

关于c++ - 控制到达非空函数的结尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9819474/

相关文章:

c++ - 字符串超出范围异常

c++ - 如何使用指针从不同的函数访问局部变量?

windows - 模糊的 Qt 快速文本

javascript - google.maps.LatLng 返回一个返回 'a' 的函数。为什么?

c++ - 如何实现无限多维数组?

c++ - 如何将枚举类型的数据保存到文件?

c++ - 如何使用 Qt(跨平台)获取列表视频捕获设备名称(网络摄像头)? (C++)

python - 如何在Python中使用return语句将局部变量传递给下一个函数

php - 如何从 MySQL 的函数返回单个值到 PHP?

c++ - C++中的递归(生成二进制代码)