函数重载在运行时如何工作?为什么重载? [英] How does function overloading work at run-time, and why overload?

查看:102
本文介绍了函数重载在运行时如何工作?为什么重载?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

比方说,我有一个名为ClothingStore的类.该类具有3个成员函数,将访问者指向商店的正确部门.成员函数为ChildrenDept,MenDept和WomenDept,具体取决于访问者是孩子,男人还是女人.

Let's say I have a class named ClothingStore. That class has 3 member functions, that point a visitor to the right department of the store. Member functions are ChildrenDept, MenDept and WomenDept, depending on whether the visitor is a child, a man or a woman.

函数重载可用于创建3个具有相同名称的函数,例如PointToDept,但采用不同的输入参数(child,man,woman).

Function overloading can be used to make 3 functions that have same name, say, PointToDept, but take different input argument ( child, man, woman ).

程序执行时在运行时实际上发生了什么?

What is actually happening on run-time when program is executing ?

我的猜测是编译器将switch语句添加到程序中,以选择正确的成员函数.但这令我感到奇怪-使用重载函数而不是使用switch语句创建自己的函数时,在程序性能方面是否有任何好处?同样,我对此部分的唯一结论是代码的可读性.谢谢.

My guess is that compiler adds switch statements to the program, to select the right member function. But that makes me wonder - is there any benefit in terms of program performance when using overloaded functions, instead of making your own function with switch statements? Again, my only conclusion on that part is code readability. Thank you.

推荐答案

来自吉恩(Gene)的评论:

From Gene's comment:

编译器会看到三个不同的函数,就像它们的名称不同一样.

The compiler sees three different functions just as though they had been differently named.

对于大多数编译器,它们的名称不同.以前称为名称修饰,其中函数名称以返回类型作为前缀,并以参数类型.

In the case of most compilers, they are differently named. This used to be called name mangling where the function name is prefixed by return type and suffixed by the parameter types.

这篇关于函数重载在运行时如何工作?为什么重载?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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