Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
I';m返回一个值,但编译器告诉我;函数必须返回一个值"; 我对C++非常陌生,我用数组编写一个栈类。我试图编译我的小程序,但我得到以下错误: Stack::pop : function must return a value._C++_Arrays_Stack - Fatal编程技术网

I';m返回一个值,但编译器告诉我;函数必须返回一个值"; 我对C++非常陌生,我用数组编写一个栈类。我试图编译我的小程序,但我得到以下错误: Stack::pop : function must return a value.

I';m返回一个值,但编译器告诉我;函数必须返回一个值"; 我对C++非常陌生,我用数组编写一个栈类。我试图编译我的小程序,但我得到以下错误: Stack::pop : function must return a value.,c++,arrays,stack,C++,Arrays,Stack,我的职能是: int pop (){ if (top < 0){ cout << "The stack is empty"; return; } return stk [top--]; } intpop(){ 如果(顶部

我的职能是:

int pop (){

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


        }
intpop(){
如果(顶部<0){

cout在所有情况下都需要返回一个值

cout << "The stack is empty";
return;
cout在以下范围内:

if (top < 0){
它不会像方法指定的那样返回int

return;

这不会返回值。您可能希望引发异常,以指示没有要返回的内容。

编译器是正确的。此行:

return;
不返回值


由于您声明函数将返回
int
,因此必须这样做。如果不能返回,则引发异常。

您可能应该修改
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
}

更好的方法是使用链表结构而不是数组结构,或者将
top
(返回top元素)与
pop
(删除top元素)分开。

如果函数不仅仅是7行(包括两行仅为大括号)这可能是一个挑战,看看<>代码>返回;在中间。认真地在请求帮助之前先阅读代码。然后再做一遍。
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;
}