为什么语言不允许通过返回值重载方法? [英] Why dont languages allow overloading of methods by return value?

查看:92
本文介绍了为什么语言不允许通过返回值重载方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

c,java和许多其他语言不注意返回值.

c, java and many other languages do not pay attention to return values.

int   i = func()
float f = func()
int   func() { return 5 }
float func() { return 1.3}

为什么上述法律不合法?会使编程变得更加困难

Why isnt the above legal? Does it make it more difficult to program

int i = func(func(func(func2(func3())))) //you dont know what you are getting

编写编译器难吗?还有更多的语言明确性吗?有没有可以做到上述目的的语言?

Is it hard to write a compiler? are there more language unambiguity? Is there a language that can do the above?

推荐答案

这种情况如何?

class A implements Foo { /*...*/ }
class B implements Foo { /*...*/ }

A func() { return new A(); }
B func() { return new B(); }

Foo v = func(); // which do you call?!

当允许重载带有不同参数的单个函数名称时,模棱两可的问题已经存在.同样必须检查返回类型可能会使解决正确的功能变得困难得多.

There are already problems with ambiguity when you allow overloading of a single function name that take different arguments. Having to check the return type as well would probably make resolving the right function a lot harder.

我确定一种语言可以实现这一点,但这会使事情变得更加复杂,并且通常会使代码更难以理解.

I'm sure a language could implement that, but it would make things a lot more complicated, and would generally make the code harder to understand.

这篇关于为什么语言不允许通过返回值重载方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆