gpt4 book ai didi

c++ - 控制到达非空函数的结尾

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:23:14 25 4
gpt4 key购买 nike

以下代码片段在编译时会产生一些警告信息:

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

警告是:

  1. 返回对局部变量“c”的引用[默认启用]
  2. 控制到达非空函数的末尾[当使用-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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com