首页 > 解决方案 > 在 C++ 中返回 Int 函数

问题描述

int r, i, arrayMinimumIndex(auto a)
{
    for (int c : a)
        c > a[r] ?: r = i, ++i;
    return r;
}

我正在尝试运行此代码,但它显示:

[Error] a function-definition is not allowed here before '{' token
[Error] 'arrayMinimumIndex' was not declared in this scope

谁能解释它为什么会失败并修复它?提前致谢

标签: c++intreturn

解决方案


正确的函数定义如下所示:

int arrayMinimumIndex(auto a) //format: return type, methode name, parameters
{
    int r = 0, i = 0; //variable definitions in the method body
    // search the index..
    return r;
}

或者

int r, i, arrayMinimumIndex(auto a);

也会起作用。r在这种情况下i是全局的。而且您仍然必须稍后实现该方法arrayMinimumIndex(见上文)。

除此之外,如果您不使用 C++11(或更高版本),调用(int c: a)将失败,因为简单数组没有实现迭代器。因此,您应该考虑通过例如一个std::vector或手动遍历数组,例如for (int i = 0; i < ...; ++i)


推荐阅读