控制到达非空函数的结束

sho*_*fee 1 c++ qt return

以下代码段在编译时会生成一些警告消息:

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

警告是:

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

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

我该如何解决这些问题?

Ton*_*nyK 6

如果你的函数可以合法地找不到匹配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
}
Run Code Online (Sandbox Code Playgroud)

但这还不行,因为它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
}
Run Code Online (Sandbox Code Playgroud)