函数重载
函数重载(Function Overload):用同一个函数名定义不同的函数,当函
数名和不同的参数搭配时函数的含义不同。
重载规则
1,函数名相同。
2,参数个数不同,参数的类型不同,参数顺序不同,均可构成重载。
3,返回值类型不影响重载。
调用准则
1,严格匹配,找到则调用。
2,通过隐式转换寻求一个匹配,找到则调用。
编译器调用重载函数的准则:
1.将所有同名函数作为候选者
2.尝试寻找可行的候选函数
3.精确匹配实参
4.通过默认参数能够匹配实参
5.通过默认类型转换匹配实参
6.匹配失败
7.最终寻找到的可行候选函数不唯一,则出现二义性,编译失败。
8.无法匹配所有候选者,函数未定义,编译失败。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
| #define _CRT_SECURE_NO_WARNINGS #include <iostream>
using namespace std;
void func(int a) { cout << "func1 " << endl; cout << a << endl; }
void func(int a, int b ) { cout << "func2" << endl; cout << a << "," <<b << endl; }
void func(int a, int b, char *str) { cout << "func3" << endl; cout << a << ", " << b << ", " << str << endl; }
void print(double a) { cout << "print double " << endl; cout << a << endl; }
void print(float a) { cout <<"print float" <<endl; cout <<a <<endl; }
#if 0 void print(int a) { cout << "print int" << endl; cout << a << endl; }
void print(char a) { cout << "print char" << endl; cout << a << endl; } #endif
int main(void) {
func(10); func(10, 20); func(10, 20, "abc");
return 0; }
|
重载底层实现(name mangling)
C++利用 name mangling(倾轧)技术,来改名函数名,区分参数不同的同
名函数。
实现原理:用 v c i f l d表示 void char int float long double 及其引
用。
1 2
| void func(char a); void func(char a,int b,double c);
|