重载:overload 同一个标识符在不同的上下文有不同的意义

1.c++中的函数重载

—-用同一个函数名定义不同的函数
—-当函数名和不同参数搭配时函数的含义不同

  1. int func(int x)
  2. {
  3. return x;
  4. }
  5. int func(int a,int b)
  6. {
  7. return a + b;
  8. }
  9. int func(const char* s)
  10. {
  11. return strlen(s);
  12. }

函数重载至少满足下面一个条件:
—-参数个数不同
—-参数类型不同
—-参数顺序不同

2.当函数默认参数遇上函数重载

int func(int a,int b,int c = 0)
{
    return a * b * c;
}

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

int main()
{
    int c = func(1,2);            //which one?

  return 0;
}

结果:test.cpp: In function ‘int main()’:
test.cpp:16: error: call of overloaded ‘func(int, int)’ is ambiguous
test.cpp:4: note: candidates are: int func(int, int, int)
test.cpp:9: note: int func(int, int)
这是c++中第一个起冲突的地方!!!其他面向对象的语言不支持参数默认值!!

3.编译器调用重载函数的准则

—-将所有同名函数作为候选者
—-尝试寻找可行的候选参数
精确匹配实参
通过默认参数能够匹配实参
通过默认类型转换匹配实参
—-匹配失败
最终寻找到的候选函数不唯一,则出现二义性,编译失败
无法匹配所有候选者,函数未定义,编译失败

4.函数重载的注意事项-函数重载的本质

—-函数重载的本质是相互独立的不同函数
—-重载函数的参数类型不同
—-函数返回值不能作为函数重载的依据,只和函数名和函数参数有关

实验:

int add(int a,int b)                    //函数类型:int(int,int)
{
    return a + b;
}

int add(int a,int b,int c)     //函数类型:int(int,int,int)
{
    return a + b +c;
}

int main()
{
    printf("%d\n",add(1,2));
  printf("%d\n",add(1,2,3));

  //函数地址,函数名就是函数的入口地址
  printf("%p\n",(int(*)(int,int))add);
  printf("%p\n",(int(*)(int,int,int))add);
  return 0;

}
结果:在符号表里面编译产生的两个函数的标识符不一样,在中间文件的obj里
另外,函数的地址也不一样:

image.png

小结:

1.函数重载是c++引入的概念
2.函数重载用于模拟自然语言的词汇搭配
3.函数重载使得c++具有更丰富的语义表达能力
4.函数重载的本质是定义了相互独立的不同函数
5.c++中通过函数名和函数参数确定函数调用