假设一个类存在如下:
class Foo
{
void do_after_something()
{
//some code here
return;
}
void do_something()
{
//some code here
return do_after_something(); //returning another (void) function
}
};
JAVA显然反对上面这样的东西,Borland C++编译器发出警告, MS VC++ 没有提示。
我的问题是:从 void 函数返回在逻辑上(理论上)是否正确?return do_after_something();
相对于:
do_after_something();
return;
或是否全部依赖于实现(编译器/语言)?
最佳答案
从哲学上讲,您可以争辩说应该允许返回 void
返回函数的结果,但不幸的是,这里不是这种情况,至少对于 Java 而言。
不过,它 对 C++ 有效。如果您尝试以下程序:
#include <iostream>
void xyzzy(void) {}
void plugh(void) { return xyzzy();}
int main() {
std::cout << "Hello\n";
plugh();
return 0;
}
它会很好地工作。
这在 ISO C++11 6.6.3/3
中有详细说明:
A return statement with an expression of type
void
can be used only in functions with a return type ofcv void
; the expression is evaluated just before the function returns to its caller.
因此,如果您认为 void
不是实际类型,而是某些东西的缺失,那么争论 Java 方法是正确的实际上同样有效。例如,当您有:
int xyzzy(void) { return 42; }
在 C 中,您不必提供正确(非)类型的参数,例如:
void plugh;
int twisty = xyzzy(plugh);
同上,C++ 方式也是正确的,但方式不同 - 语言就是它们本身。
关于java - 从 void 函数返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27142891/