What is the use/advantage of function overloading?

2019-01-17 15:29发布

What is the use/advantage of function overloading?

10条回答
The star\"
2楼-- · 2019-01-17 16:10
Emotional °昔
3楼-- · 2019-01-17 16:11

A function/method is sometimes able to take different kinds of parameters in order to do it's job. This is the time for function overloading. Otherwise, you would have to have different functions for the same functionality, which is confusing and bad practice.

  • Constructors are functions, so they can be overloaded. This is very handy.
  • When you first get into overloading, it's easy to get over-fancy, thinking you're doing future developers a favor by giving them more convenient options. Try to avoid this. Unneeded overloads can confuse future developers and cause unnecessary code to maintain.
查看更多
男人必须洒脱
4楼-- · 2019-01-17 16:16

Very valid question.

You get consistency in naming, but at the cost of ambiguity about exact implementation.

  • The real issue is human memory for method names, right? we find it easier to remember names that are commonly used.

  • and economy of typing, allowing for shorter method names? fewer different names means (mathematically) that the name itself carries less information.

These two issues shouldn't be any concern, with IDEs that find/guess/insert method names rapidly based on the first few characters, and parameter/return types.

But I do think there is a cost, in preciseness of coding, as well as a benefit.

查看更多
放我归山
5楼-- · 2019-01-17 16:16

It providing multiple behaviour to same object with respect to attributes of object.

For example a method called addUs(a,b) adds a and b.

So the definition will be:

int addUs(int a, int b){
  return a+b;
}

But now if you want your arguments to be Objects of a class say:

class Demo{
  int height;
  int width;
}

You want the same function addUs() to return a new object which would have attributes height and width having values as sum of the height & width of the 2 arguments passed.

So now the definition would be:

Demo addUs(Demo a Demo b){
  Demo this;
  this.height = a.height + b.height;
  this.width = a.width + b.width;
  return this;
}
查看更多
登录 后发表回答