我返回一个值,但编译器告诉我"function must return a value"

I'm returning a value but the compilers tells me "function must return a value"

本文关键字:告诉我 编译器 function must value return 返回 一个      更新时间:2023-10-16

我对C++很陌生,我正在使用数组编写堆栈类。我正在尝试编译我的小程序,但出现以下错误:

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;

不返回任何内容。

您需要返回一个在正常使用中永远不会返回的值,或者将return替换为 throw

在:

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(返回顶部元素)与pop(删除顶部元素)分开。