Return 调用函数的语句 returns void 在 returns void 的函数中
Return statement that calls a function that returns void in a function that returns void
当使用函数 return 值时,以下代码在 g++ 中编译和工作。有一个 return 无效的方法,它在 return 语句中调用另一个 return 无效的函数。我的问题是为什么 g++ 允许这种行为?
#include <iostream>
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Boo()
{
return ( Foo() );
}
int main()
{
Boo();
return ( 0 );
}
void
是一种在某些情况下可以与其他类型互换使用的类型。如果 Boo
和 Foo
returned int
,您的示例将非常有意义;为什么更改类型应该是正确语义的特殊例外?
return (Foo())
本质上是在说 "return nothing,",实际上是 Boo
声明的 return 类型。你会发现
void bar() {
return void();
}
编译得很好。
根据CPP Reference,当调用return expression;
时:
The expression is optional in functions whose return type is (possibly cv-qualified) void, and disallowed in constructors and in destructors.
后来,他们注意到:
In a function returning void, the return statement with expression can be used, if the expression type is void.
return
可以有一个 void 函数的表达式,只要该表达式也是 void,这就是您所做的。这在模板中可能很有用,在模板中,函数的 return 类型在编写函数时可能是未知的。
当使用函数 return 值时,以下代码在 g++ 中编译和工作。有一个 return 无效的方法,它在 return 语句中调用另一个 return 无效的函数。我的问题是为什么 g++ 允许这种行为?
#include <iostream>
void Foo()
{
std::cout << "Foo" << std::endl;
}
void Boo()
{
return ( Foo() );
}
int main()
{
Boo();
return ( 0 );
}
void
是一种在某些情况下可以与其他类型互换使用的类型。如果 Boo
和 Foo
returned int
,您的示例将非常有意义;为什么更改类型应该是正确语义的特殊例外?
return (Foo())
本质上是在说 "return nothing,",实际上是 Boo
声明的 return 类型。你会发现
void bar() {
return void();
}
编译得很好。
根据CPP Reference,当调用return expression;
时:
The expression is optional in functions whose return type is (possibly cv-qualified) void, and disallowed in constructors and in destructors.
后来,他们注意到:
In a function returning void, the return statement with expression can be used, if the expression type is void.
return
可以有一个 void 函数的表达式,只要该表达式也是 void,这就是您所做的。这在模板中可能很有用,在模板中,函数的 return 类型在编写函数时可能是未知的。