【问题标题】:C++ There is a bool return type function returning (24) hereC++这里有一个bool返回类型函数返回(24)
【发布时间】:2019-12-16 20:55:55
【问题描述】:

首先抱歉代码太多

这里有一个类型为class的vector(teamNum),该class包含一个struct类型的v​​ector(player),有点复杂,但是在这个函数中我需要检查teamNum中是否有player包含 tName 等于 _tname(函数参数) 包含(播放器)pID 等于 _pID(函数参数)

bool thereIsSimilarID(string _tname, int _pID)
{
for (int i = 0; i < teamNum.size(); i++)
{
    if (teamNum[i].tName == _tname)
    {
        for (int j = 0; j < teamNum[i].player.size(); j++)
        {
            if (teamNum[i].player[j].pID == _pID)
                return true;
        }
    }
    else if (i == (teamNum.size() - 1))
    {
        return false;
    }
}

}

主要是

int main()
{
     cout << "\n" << thereIsSimilarID("Leverpool", 1) << endl;
}

输出是 24 !!!!!! (请注意,这只发生在球队(Leverpool)是向量 teamNum 中的最后一支球队时)

再次抱歉代码太多,但我需要知道错误不仅解决了我需要向你学习的问题

【问题讨论】:

  • [Off Topic] 去掉else if (i == (teamNum.size() - 1)) { return false; },把return false;放在for循环后面。
  • 你能提供一个minimal reproducible example吗?
  • 如果teamNum.size() == 0 怎么办?整个for 循环被跳过,返回值是---¯\_(ツ)_/¯。实际上,行为是未定义的。
  • 您的编译器应该警告您存在不会导致return 语句的代码路径。返回值在这些路径中是未指定

标签: c++ function boolean


【解决方案1】:

您遇到了未定义的行为。

如果您在最后一个元素上使用if (teamNum[i].tName == _tname)-branch,但找不到具有正确 pID 的玩家,则不会返回任何内容。这意味着,返回值是当前内存位置中应该保存返回值的任何随机值。在你的情况下,它发生在 24 岁。但理论上,一切都可能发生。

teamNum 为空时也会出现同样的问题。

解决方案是确保始终从函数返回一个值(当然,除非它具有返回类型 void):

bool thereIsSimilarID(string _tname, int _pID)
{
    for (int i = 0; i < teamNum.size(); i++)
    {
        // In this loop return true if you find a matching element
    }

    // If no matching element was found we reach this point and make sure to return a value
    return false;
}

您应该查看您的编译器设置并启用所有警告。通常最好让它将某些警告视为错误。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    • 2023-02-10
    • 1970-01-01
    • 2011-06-07
    相关资源
    最近更新 更多