我正在试验现代的C++ 'auto‘,并找到了一个简单的例子,它会产生一个错误,但我不明白为什么:
main.cpp
// error: use of ‘auto test(int)’ before deduction of ‘auto’ int i = test(5);
int i = test(5);test.h
auto test(int i);test.cpp
auto test(int i) {
if (i == 1)
return i; // return type deduced as int
else
return Correct(i-1)+i; // ok to call it now
}但是,如果我使用'->‘->指定类型,代码就会生成并运行良好。例如:
auto test(int i) -> int;g++ 6.2是编译器的现代版本,我想知道为什么我必须使用'-> int‘。谢谢你的建议。
发布于 2017-01-12 15:33:08
返回类型推断根本不能用于声明。编译器使用定义(实现)通过检查函数实际返回的内容来推断类型。在声明中不可能这样做,所以当调用函数时编译将失败,因为还没有推断的返回类型。
使用尾部返回类型时,将显式指定返回类型。在您的示例中,它与使用旧的“正常”方式声明返回类型没有什么不同。
https://stackoverflow.com/questions/41617005
复制相似问题