簡體   English   中英

警告C4715:“ operator ==”:並非所有控制路徑都返回值

[英]warning C4715: 'operator==' : not all control paths return a value

我不斷收到此錯誤,但我不明白為什么。 編譯器告訴我它在本節中。

任何幫助將不勝感激

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){

    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;
}

錯誤消息告訴您出了什么問題。

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
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM