重载与指针

函数重载遇上函数指针

将重载函数名赋值给函数指针时

根据重载规则挑选与函数指针参数列表一致的候选者

严格匹配候选者的函数类型与函数指针的函数类型

#include <stdio.h>
#include "string.h"

int func(int x)
{
    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 main(int argc, char *argv[])
{
    int c = 0;
    PFUNC p = func;
    c = p(1);
    printf("c = %d\n",c);
   
    return 0;
}

输出:
c = 1;

重载与指针

注意

函数重载必然发生在同一个作用域中

编译器需要用参数列表或函数类型进行函数选择

无法直接通过函数名得到重载函数的入口地址

#include <stdio.h>
#include "string.h"

int add(int x,int y)//int(int,int)
{
    return x+y;
}
int add(int a,int b,int c) //int(int,int,int)
{
    return a + b + c;
}


int main(int argc, char *argv[])
{
   printf("%p\n",(int(*)(int,int))add);
   printf("%p\n",(int(*)(int,int,int))add);
   return 0;
}

C++和C相互调用

实际工程中C++和C代码相互调用是不可避免的

C++编译器能够兼容C语言的编译方式

C++编译器会优先使用C++编译的方式

extern 关键字能够强制C++编译器进行C方式的编译

image.png

delphi@delphi-vm:~/9-2$ gcc -c add.c -o add.o
delphi@delphi-vm:~/9-2$ g++ main.cpp add.o
delphi@delphi-vm:~/9-2$ ./a.out
c = 3
delphi@delphi-vm:~/9-2$ 

Slide9.PNG

_cplusplus 是C++编译器内置的标准宏文件

_cplusplus的意义

确保C代码以统一的C方式被编译成目标文件

小结

函数重载是C++对C的一个重要升级

函数重载通过函数参数列表区分不同的别名函数

extern关键字能够实现c和C++的相互调用

编译方式决定符号表中的函数名的最终目标名


YingLi
6 声望5 粉丝

From zero to hero.