控制到达bool函数中非void函数的结束

Control reaches end of non void function in bool function

本文关键字:函数 void 结束 bool 控制      更新时间:2023-10-16

这是我目前正在处理的代码,我似乎无法找出一种方法来使这个函数停止抛出"控制达到非无效函数的结束"错误。else语句不应该捕捉if语句没有捕捉到的东西并返回真或假吗?

bool operator == (const MyInt& x, const MyInt& y)
{
    if (x.currentSize != y.currentSize)
    {
        return false;
    }
    else
    {
        for (int i = 0; i < x.currentSize; i++)
        {
                if (x.integer[i] != y.integer[i])
                {
                    return false;
                    break;
                }
                else
                    return true;
        }
    }
}

如果x.currentsize == 0y.currentsize == 0,那么您将永远不会达到return语句。

我感觉你打算写下面的代码。请注意,我们只在测试了整个列表后才使用return true

bool operator==(const MyInt& x, const MyInt& y)
{
    if (x.currentSize != y.currentSize)
        return false;
    for (int i = 0; i < x.currentSize; i++)
        if (x.integer[i] != y.integer[i])
            return false;
    return true;
}

你必须在第一个else上放一个return,以防你的方法没有经过for循环,例如,当x.currentSize = 0

同样,你的if条件总是在第一次迭代后返回一个值,所以你应该这样改变它,这样你就可以检查Array

中的所有元素
bool operator == (const MyInt& x, const MyInt& y)
{
    if (x.currentSize != y.currentSize)
    {
        return false;
    }
    else
    {
        for (int i = 0; i < x.currentSize; i++)
                if (x.integer[i] != y.integer[i])
                    return false;
        return true;
    }
}

这种错误的一般原因是代码不好,难以阅读。

按如下方式重写函数

bool operator ==( const MyInt &x, const MyInt &y )
{
    if ( x.currentSize == y.currentSize )
    {
        int i = 0;
        while (  i < x.currentSize && x.integer[i] == y.integer[i] ) i++;
        return ( i == x.currentSize );
    }
    return ( false );
}

或者如果integer是指针或数组,则可以应用标头<algorithm>中声明的标准算法std::equal。例如

#include <algorithm>
//...
bool operator ==( const MyInt &x, const MyInt &y )
{
    return ( x.currentSize == y.currentSize && 
             std::equal( x.integer, x.integer + x.currentSize, y.integer ) );
}
我认为这段代码看起来好多了,不是吗?