0

私は C++ の初心者で、配列を使用してスタック クラスを作成しています。小さなプログラムをコンパイルしようとしていますが、次のエラーが発生します。

Stack::pop : function must return a value.

私の機能はこれです:

int pop (){

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


        }
4

5 に答える 5

0

おそらく、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(最上位の要素を返す) from pop(最上位の要素を削除する) を分離することです。

于 2013-11-12T18:15:18.817 に答える