以下代码片段在编译时会生成一些警告消息:
Cluster& Myclass::getCluster(const Point &p)
{
foreach (Cluster c, *this)
foreach (Point point, c)
if (point == p)
return c;
}
警告是:
- 返回对局部变量“c”的引用[默认启用]
- 控制到达非 void 函数的末尾 [当使用
-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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)