在函数原型中省略 return 类型
Omit return type in function prototype
来自 C++ 学院文档(在线课程):
return_type describes the type of result returned (delivered) by the function (e.g. we expect that the sine function will return a value of type float as int data is completely unusable in this context); you can use any of the C++ types as a return_type, including a very special type named void; a function of type void returns no result at all; we can say that such a function may have an effect but definitely has no result; if you omit the return_type, the compiler assumes that the function returns a value of type int
关于这个例子return_type function_name (parameters_list);
在这个例子中:
my_function(int x) {
return 4;
}
int main()
{
...
}
我收到以下错误:ISO C++ forbids declaration of 'my_function' with no type [-fpermissive]|
在这个例子中:
my_function(int); //Prototype
int main()
{
...
}
int my_function(int x)
{
return 4;
}
我收到以下错误:expected constructor, destructor, or type conversion before ';' token
我在 C++11 standard 第 192 页中没有找到 - function declaration
与我想知道的内容相关的内容(或者可能只是我不明白的事实)。
能否请您解释一下什么时候可以省略return_type?这是一个错误吗?或者是一些旧版本的 C++?
Could you please explain when can be omitted the return_type? Is this a mistake?
return 类型不能在常规函数原型中省略。您引用的资源提出其他建议是非常错误的。标准 C++ 中没有规则假定函数原型中的 return 类型为 int
。
Or is some older version of C++?
不是 C++。 C++ 不允许省略 return 类型。但是预先标准化的 C (K&R C) 确实允许它并且有一个 "implicit int" 规则。因此,一些编译器提供了与一些非常古老的 C 代码兼容的扩展。
但同样,这不是,也从来不是标准 C++。
来自 C++ 学院文档(在线课程):
return_type describes the type of result returned (delivered) by the function (e.g. we expect that the sine function will return a value of type float as int data is completely unusable in this context); you can use any of the C++ types as a return_type, including a very special type named void; a function of type void returns no result at all; we can say that such a function may have an effect but definitely has no result; if you omit the return_type, the compiler assumes that the function returns a value of type int
关于这个例子return_type function_name (parameters_list);
在这个例子中:
my_function(int x) {
return 4;
}
int main()
{
...
}
我收到以下错误:ISO C++ forbids declaration of 'my_function' with no type [-fpermissive]|
在这个例子中:
my_function(int); //Prototype
int main()
{
...
}
int my_function(int x)
{
return 4;
}
我收到以下错误:expected constructor, destructor, or type conversion before ';' token
我在 C++11 standard 第 192 页中没有找到 - function declaration
与我想知道的内容相关的内容(或者可能只是我不明白的事实)。
能否请您解释一下什么时候可以省略return_type?这是一个错误吗?或者是一些旧版本的 C++?
Could you please explain when can be omitted the return_type? Is this a mistake?
return 类型不能在常规函数原型中省略。您引用的资源提出其他建议是非常错误的。标准 C++ 中没有规则假定函数原型中的 return 类型为 int
。
Or is some older version of C++?
不是 C++。 C++ 不允许省略 return 类型。但是预先标准化的 C (K&R C) 确实允许它并且有一个 "implicit int" 规则。因此,一些编译器提供了与一些非常古老的 C 代码兼容的扩展。
但同样,这不是,也从来不是标准 C++。