【问题标题】:Return in Int Function in C++在 C++ 中返回 Int 函数
【发布时间】:2019-11-07 09:50:19
【问题描述】:
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

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

【问题讨论】:

  • 你希望语法 int r, i, arrayMinimumIndex 做什么?
  • 注意std::min_element 存在。
  • 您收到这些错误是因为这不是有效的 cpp 语法。
  • 函数声明的正确语法如下:return_type function_name(argument_list){}。那里没有逗号(() 中的参数列表除外)。如果你试图返回多个元素,这是不可能的——你必须将它们组合在一个结构中或使用std::pair/std::tuple。你可能想得到a good C++ book 学习
  • 您不要在返回类型后添加任何变量名。只有函数名。答案中显示了声明函数的正确方法,但如果您的书/教程/课程没有解释这一点,您真的应该考虑获得更好的方法。

标签: c++ int return


【解决方案1】:

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

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);

也可以。 ri 在这种情况下是全局的。您仍然需要稍后实现 arrayMinimumIndex 方法(见上文)。

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

【讨论】:

  • 您修复的代码是正确的,但这不是我想要的,我不明白为什么我要编写如下函数: int i, r arrayMinimumIndex(auto a) 但在其他编译器中,它仍然作品
  • @Ducanh Tran:那会是哪个编译器?
  • @DucanhTran 正如我在 cmets 中链接到的问题 none of 3 major C++ compilers accept your code。答案中建议的拆分声明和定义可能会编译。
  • @problematicDude:这是一个简单的声明,就像int arrayMinimumIndex(auto a);int r, i;一样,区别只是在一行中声明。
  • @problematic Dude:你甚至可以将两个方法声明放在一行中int r(int), w(int); ;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-02-09
  • 1970-01-01
  • 1970-01-01
  • 2012-04-22
  • 2018-11-19
  • 1970-01-01
相关资源
最近更新 更多