本文介绍了控制到达非空函数的结尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
以下代码片段在编译时会生成一些警告消息:
The following code snippet generates some warning messages when compiling:
Cluster& Myclass::getCluster(const Point &p)
{
foreach (Cluster c, *this)
foreach (Point point, c)
if (point == p)
return c;
}
警告是:
- 对局部变量c"的引用返回[默认启用]
- 控制到达非空函数的结尾[使用
-Wreturn-type
时]
我知道如果条件失败,我不会返回值.但是,当我尝试 return 0
时,它给了我错误.
I know that I am not returning a value if the condition fails. However, when I try return 0
it gave me error.
我该如何解决这些问题?
How can I solve these issues?
推荐答案
如果您的函数可以合法地无法找到匹配的Cluster
,那么您应该让它返回一个指针:
If your function can legitimately fail to find a matching Cluster
, then you should have it return a pointer:
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
是一个局部变量.所以你把它作为一个参考,像这样:
But this doesn't work yet, because c
is a local variable. So you make it a reference, like this:
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
}
这篇关于控制到达非空函数的结尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!