以下代码片段在编译时会产生一些警告信息:
Cluster& Myclass::getCluster(const Point &p)
{
foreach (Cluster c, *this)
foreach (Point point, c)
if (point == p)
return c;
}
警告是:
- 返回对局部变量“c”的引用[默认启用]
- 控制到达非空函数的末尾[当使用
-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/