我返回一个值,但编译器告诉我"function must return a value"
I'm returning a value but the compilers tells me "function must return a value"
我对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
(删除顶部元素)分开。
相关文章:
- 我看到"use of undeclared identifier"错误,有人可以告诉我如何解决它吗?
- 谁能告诉我我用 getline 做错了什么 (cpp) 格式
- 比特集告诉我的名字是什么?
- 我试图用这段代码找到二叉树的高度,但它一直返回 0,有人可以告诉我为什么吗?
- 任何人都可以告诉我我的 C++ 代码出了什么问题?
- 我可以让 valgrind 告诉我 _哪个_值未初始化吗?
- 程序告诉我,即使它们明显匹配,参数也不匹配
- 谁能告诉我为什么这段代码没有产生正确的输出?
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 为什么 gcc 告诉我我的模板不是模板?
- 代码以查找数组中的最大数字,但它仅将第一个数字显示为最大数字. 有人请告诉我为什么
- 关于这个在 Linux 上使用 gcc 编译的程序中的 vtable,nm 告诉我什么?
- 告诉我如何填充二维数组
- 我找不到瓦尔格林德告诉我的记忆链接
- 如何将char数组声明为函数参数?或告诉我此代码中还有其他问题?
- 合成错误不知道为什么会发生这种情况,请检查一下并告诉我这是我的编码还是视觉工作室
- 可以编译器告诉我它选择的哪个超载或模板功能
- 我返回一个值,但编译器告诉我"function must return a value"
- 编译器告诉我它无法解析重载函数的地址.对于 switch() 语句,这意味着什么
- 为什么编译器告诉我<string>向量没有声明?