C++_09_函数重载
函数重载
函数重载概念(Function Overload):
同一个函数名搭配不同(类型和数量)的参数,这就是函数重载
注意:函数名和不同参数搭配时函数的含义不同,重载的函数(函数体)自然是不同的
函数重载判断标准:
1、参数个数不同
2、参数类型不同
3、参数顺序不同
注意:函数返回值不是函数重载的判断标准
重载函数调用标准:
1、传入实参要求唯一性,不能出现一个实参能匹配两个重载函数的状况
2、默认参数和重载参数回合在一起,是否允许完全取决于最终匹配到的函数是否唯一
#include<iostream> using namespace std; void fun(int a,int b,int c=0) { cout << "这是函数重载1" << endl; } void fun(int a,int b) { cout << "这是函数重载2" << endl; } int main(int argc, char const *argv[]) { // fun(1,1); //error 会导致函数重载二义性 fun(1,1,1); return 0; }
zl@LAPTOP-2ABL2N6V:/mnt/d/VsCode$ ./08-默认参数函数重载 这是函数重载1 zl@LAPTOP-2ABL2N6V:/mnt/d/VsCode$
函数重载和函数指针
函数指针表示函数调用入口地址,通过指针(入口地址)可以执行函数
将重载函数赋值给函数指针的时候,可以通过指针传参个数来匹配相对应的重载函数执行(解决不知道执行哪个重载函数的问题,通过指针传参个数来匹配相对应的重载函数)
int func(int x) // int(int a) { return x; } int func(int a, int b) { return a + b; } int func(const char* s) { return strlen(s); } typedef int(*PFUNC)(int a); // int(int a) int main() { int c = 0; PFUNC p = func;
函数重载和函数指针在一起
#include <iostream> using namespace std; void myfunc(int a) { printf("a:%d \n", a); } void myfunc(char *p) { printf("%s \n", p); } void myfunc(int a, int b) { printf("a:%d \n", a); } void myfunc(char *p1, char *p2) { printf("p1:%s ", p1); printf("p2:%s \n", p2); } //函数指针 基础的语法 //1声明一个函数类型 typedef void (myTypeFunc)(int a,int b) ; //int //myTypeFunc *myfuncp = NULL; //定义一个函数指针 这个指针指向函数的入口地址 //声明一个函数指针类型 typedef void (*myPTypeFunc)(int a,int b) ; //声明了一个指针的数据类型 //myPTypeFunc fp = NULL; //通过 函数指针类型 定义了 一个函数指针 , //定义一个函数指针 变量 void (*myVarPFunc)(int a, int b); // void main() { myPTypeFunc fp; //定义了一个 函数指针 变量 fp = myfunc; //fp(1); //myVarPFunc = myfunc; fp(1, 2); /* { char buf1[] = "aaaaafff"; char buf2[] = "bbbb"; fp(buf1, buf2); } */ cout<<"hello..."<<endl; system("pause"); return ; }

浙公网安备 33010602011771号