以下代码段在编译时会生成一些警告消息:
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)
警告是:
-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
}
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)