函数的重载
一. 重载的概念
-
同一个标识符在不同的上下文有不同的意义
如:
play chess、play the piano、 play bascketball 、play the guitar 、play the ukulele
二. swap函数的局限
上面我们用引用定义行参,也可以实现swap函数,但是还是有可以改进的地方,上述的swap()只能交换两个整数类型的变量,如何实现使用同一个函数名,但是可以实现不同数据类型两个变量的交换
三. 函数重载(function overload)
-
用同一个函数名定义不同的函数
#include<iostream> using namespace std; void swap(int& a, int& b) { int tmp = a; a = b; b = tmp; } void swap(float& a, float& b) { float tmp = a; a = b; b = tmp; } void swap(char& a, char& b) { int tmp = a; a = b; b = tmp; } int main(int argc, const char *argv[]) { int ai = 10; int bi = 20; swap(ai, bi); cout << "ai = " << ai << " bi = " << bi << endl; float af = 12.34; float bf = 56.78; swap(af, bf); cout << "af = " << af << " bf = " << bf << endl; char ac = 'a'; char bc = 'b'; swap(ac, bc); cout << "ac = " << ac << " bc = " << bc << endl; return 0; }
-
当函数名和不同的参数搭配时函数的含义不同
-
函数重载至少满足下面一个条件
-
参数个数不同、数类型不同、参数顺序不同
#include<string> #include<iostream> using namespace std; int fun(int a) { return a; } int fun(int a, int b) { return a+b; } int fun(string s) { return s.length(); } int main(int argc, const char *argv[]) { int a = 10; int b = 20; string str = "hello"; cout << "fun(a)" << fun(a) << endl; cout << "fun(a+b)" << fun(a+b) << endl; cout << "fun(str)" << fun(str) << endl; return 0; }
$ ./a.out fun(a)10 fun(a+b)30 fun(str)5
四. C++中的函数重载
- 函数重载的本质为相互独立的不同函数
- C++中通过函数名和函数参数确定函数调用
- 无法直接通过函数名得到重载函数的入口地址
- 函数重载必然发生在同一个作用域中
五. 重载的意义
- 通过函数名对函数功能进行提示
- 通过参数列表对函数函数用法进行提示
- 扩展系统中已经存在的函数功能
六. 重载的实现原理
通过查看反汇编代码:objdump -D a.out > a.dis