我很好奇在C ++ 11中使用auto关键字。
对于函数定义,必须编写函数的返回类型:
auto f (int x) -> int { return x + 3; }; //success
auto f (int x) { return x + 3; }; //fail
但是在这个例子中,它们都可以工作:
auto f = [](int x) { return x + 3; }; //expect a failure but it works
auto f = [](int x) -> int { return x + 3; }; // this is expected code
感谢。
答案 0 :(得分:5)
在C ++ 11中,lambda表达式可以省略其返回类型,如果它可以推导出没有歧义的确切表达式。但是,此规则不适用于常规函数。
int f() { return 0; } // a legal C++ function
auto f() -> int { return 0; } // a legal C++ function only in C++11
auto f() { return 0; } // an illegal C++ function even if in C++11
答案 1 :(得分:0)
如果您需要在" - >"之后指定退货类型(因为它在C + 11中) - 有什么意义?" auto"在函数声明中?这就像是说:"这个函数可以返回任何东西,但实际上它只是这种类型"。呃?
然后,如果您不需要在" - >"之后指定退货类型。 (就像在C ++ 14中一样):想象你没有函数的源代码,而是对象文件和标题。你怎么知道函数返回的内容(返回类型)?
到目前为止似乎" auto"在函数声明中是编写不可读代码的另一种方法。好像在C ++中已经没有足够的方法来实现它了。
在内部功能体内" auto"是一个很好的语法糖"。
或者我错过了什么?