<分区>
我最近读到 C++ 中所有函数的默认返回类型都是 int
。谷歌搜索这并不能帮助我确认这一点。
所以:
- 真的是 C++
int
中所有函数的默认返回类型吗? - 如果没有,那么 C++ 中的函数是否存在任何此类默认返回类型?如果是,那是什么?
<分区>
我最近读到 C++ 中所有函数的默认返回类型都是 int
。谷歌搜索这并不能帮助我确认这一点。
所以:
int
中所有函数的默认返回类型吗?最佳答案
- Is really the default return type for all functions in C++
int
?
没有。
- If not, then does any such default return type exists for functions in C++ ?
没有。
让编译器来帮你。如果您尝试按照以下方式做某事,
noReturnType(int a, int b)
{
std::cout << a + b << "\n";
}
你会得到例如
error: C++ requires a type specifier for all declarations noReturnType(int a, int b) ^
这可以通过在函数声明/定义(或您打算返回的任何类型)前添加 void
来缓解。一个可能被混淆的机会是让编译器推断返回类型的能力。这个例子在 C++14 下编译得很好:
auto deduceReturnType(int a, int b)
{
return a + b; // return type is int
}
但这与默认返回类型无关,也不能省略此处的auto
。
关于c++ - C++ 中的函数是否有任何默认返回类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56477746/