c++ - C++ 中的函数是否有任何默认返回类型?

标签 c++ c++11

<分区>

我最近读到 C++ 中所有函数的默认返回类型都是 int。谷歌搜索这并不能帮助我确认这一点。

所以:

  1. 真的是 C++ int 中所有函数的默认返回类型吗?
  2. 如果没有,那么 C++ 中的函数是否存在任何此类默认返回类型?如果是,那是什么?

最佳答案

  1. Is really the default return type for all functions in C++ int?

没有。

  1. 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/

相关文章:

c++ - typedef vector

C++ 菱形接口(interface)继承

c++ - 为什么 uniform_int_distribution<uintmax_t> 适用于 62 位数字但不适用于 63 或 64 位数字?

c++ - 在运行时获取类型参数

c++ - 在 =delete 的含义中使用 =default

c++ - 如何为 QtWebKit 安装插件

c++ - 使编译器在类型删除中使用 lambda 优化函数调用间接

c++ - <cstdint> 与 std::size_t 类型

c++ - 我可以为不同的类型集定义模板吗?

C++ 多线程 : What happens if destructor and member function are running in separate threads