簡體   English   中英

我正在返回一個值,但是編譯器告訴我“函數必須返回一個值”

[英]I'm returning a value but the compilers tells me “function must return a value”

我是C ++的新手,並且正在使用數組編寫Stack類。 我正在嘗試編譯我的小程序,但出現以下錯誤:

Stack::pop : function must return a value.

我的功能是這樣的:

int pop (){

            if (top < 0){
                cout << "The stack is empty";
                return;
            }
            return stk [top--];


        }

編譯器是正確的。 這行:

return;

不返回值。

由於您聲明函數將返回int ,因此必須這樣做。 否則拋出異常。

在所有情況下都需要返回一個值

cout << "The stack is empty";
return;

不返回任何東西。

您需要返回一個在正常使用中永遠不會返回的值,或者用throw代替return

在:

if (top < 0){

阻止你有:

return ;

它不返回方法指定的int值

return;

那不會返回值。 您可能想拋出一個異常,以表示沒有任何返回值。

您可能應該修改pop函數的實現。 您的問題記錄如下:

int pop ()
{
    if (top < 0) // how is top negative???
    {
        cout << "The stack is empty";
        return; // doesn't return anything - this is your compiler error
    }
    return stk [top--]; // you probably do not want to use this approach
}

更好的方法可能如下所示:

int pop ()
{
    if (size == 0)
    {
        throw std::out_of_range("The stack is empty");
    }
    size -= 1;
    int result = stk[size];
    return result;
}

更好的方法是使用鏈表結構而不是數組結構,或者將top (返回top元素)與pop (刪除top元素)分開。

暫無
暫無

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

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