c++ - "not in this scope"cpp函数调用错误

标签 c++ function parameters scope

我试图在 cpp 中实现合并排序。但是,Dev-cpp 5.6.1 报告了一些“不在此范围内”的错误。它说,“lo”、“mid”和“hi”没有在此范围内声明。你能告诉我为什么会这样吗?谢谢。

#include<iostream>
using namespace std;
void merge(int nums[], int lo, int mid, int hi) {
    int n1 = mid - lo + 1;
    int n2 = hi - mid + 1;
    /*Other implementation code omitted*/
}
int main() {
    /*code to Input numbers into nums[]*/
    merge(nums, 0, 4, 9);
    return 0;
}

最佳答案

阅读涉及语法错误的错误消息时,最重要的是要特别注意第一条。这是因为 C++ 编译器没有义务在出现第一个错误时停止,并且第一个错误可能会产生更多错误。

在您的原始代码中,您在merge() 函数的nums 参数声明中存在语法错误:

#include<iostream>
using namespace std;
int nums[10];
void merge(int[] &nums, int lo, int mid, int hi) {
    int n1 = mid - lo + 1;
    int n2 = hi - mid + 1;
    /*Other implementation code omitted*/
}
int main() {
    /*code to Input numbers into nums[]*/
    merge(nums, 0, 4, 9);
}

您已经编辑了您的程序以消除该语法错误,但是对于这个原始代码,我看到了以下错误消息:

x.cc:3: error: expected ',' or '...' before '&' token
x.cc: In function 'void merge(int*)':
x.cc:4: error: 'mid' was not declared in this scope
x.cc:4: error: 'lo' was not declared in this scope
x.cc:5: error: 'hi' was not declared in this scope
x.cc: In function 'int main()':
x.cc:3: error: too many arguments to function 'void merge(int*)'
x.cc:11: error: at this point in file

您报告了 was not declared in this scope 错误,但没有提及第一个错误,即指出 nums 的语法错误。由于此语法错误,编译器无法解析其余函数参数,因此报告这些标识符没有可见声明。

修复此错误会移除其他错误。这是因为函数原型(prototype)的解析器现在获取函数参数的其余部分,因此它们现在在函数其余部分的范围内。

关于c++ - "not in this scope"cpp函数调用错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26351670/

相关文章:

java - 如何在retrofit2中设置参数列表

c++ - 引用的内存分配

c++ - 你如何从一个更大的函数创建一个更小的函数?

azure - Python Azure函数: Runtime is unreachable 503 error

C++ 使用可变参数模板绑定(bind)成员函数

ajax - 从客户端查询时,带参数的 Express.js 路由会产生 404

c - 如何使用 gcc 将变量传递给 C 程序

c++ - 将数组绑定(bind)到sql参数

模板对象的 C++ 继承(G++ 编译器)

C++0x:std::function::target 和模板参数出错