警告 C4715:"运算符==":并非所有控制路径都返回值



我一直收到此错误,我不明白为什么。编译器告诉我,它就在本节中。

任何帮助将不胜感激

bool operator==(const Bitmap& b1, const Bitmap& b2){
    // TODO: complete the == operator
    if ((b1.height == b2.height) && (b1.width == b2.width))
    {
        for (int r = 0; r < b1.height; r++)
        {
            for (int c = 0; c < b1.width; c++)
            {
                if (b1.get(r, c) == b2.get(r, c))
                {
                }
                else
                    return false;
            }
        }
    }
    else
        return false;
}

编译器的诊断正是它所说的。

请注意,如果 for 循环一直运行到最后,而不采用返回 false 的 if 条件,如果 r 达到 b1.height 值,则执行路径将到达此函数的末尾,而无需显式return

错误消息说明了问题所在。

bool operator==(const Bitmap& b1, const Bitmap& b2){
    // TODO: complete the == operator
    if ((b1.height == b2.height) && (b1.width == b2.width))
    {
        for (int r = 0; r < b1.height; r++)
        {
            for (int c = 0; c < b1.width; c++)
            {
                if (b1.get(r, c) == b2.get(r, c))
                {
                }
                else
                    return false;
            }
        }
        return true; // I guess you forgot this line
    }
    else
        return false;
}

嗯,这正是错误所说的。编译器不知道是否有可能触发嵌套 for 循环中的代码。假设第一个条件为真,则代码可能永远不会到达 return 语句。因此,编译器将确保始终返回某些内容,无论您给出什么条件。

bool operator==(const Bitmap& b1, const Bitmap& b2){
if ((b1.height == b2.height) && (b1.width == b2.width))
{
    // The compiler expects a return statement that is always reachable inside this if.
    for (int r = 0; r < b1.height; r++)
    {
        for (int c = 0; c < b1.width; c++)
        {
            if (b1.get(r, c) == b2.get(r, c))
            {
            }
            else
                return false; //This isn't always reachable.
        }
    }
}
else
    return false; // This case is covered, so nothing wrong here.
}

这很简单。

bool operator==(const Bitmap& b1, const Bitmap& b2){
// TODO: complete the == operator
if ((b1.height == b2.height) && (b1.width == b2.width))
{
for (int r = 0; r < b1.height; r++)
{
    for (int c = 0; c < b1.width; c++)
    {
        if (b1.get(r, c) == b2.get(r, c))
        {
        }
        else
            return false;
    }
}
// if your function runs to end of for loop, you get to here
}
else
    return false;
//then here
return false;   //<-- add this
}

错误消息非常清楚。

bool operator==(const Bitmap& b1, const Bitmap& b2){
    if ((b1.height == b2.height) && (b1.width == b2.width))
    {
        for (int r = 0; r < b1.height; r++)
        {
            for (int c = 0; c < b1.width; c++)
            {
                ...
            }
        }
        return ???;   // What should be returned here?
    }
    else
        return false;
}

最新更新