版权声明:本文为博主原创文章,转载请注明出处! https://blog.csdn.net/qq_27513221/article/details/79837960
一、重载与指针
下面的函数指针将保存哪个函数的地址?
- 函数重载遇上函数指针
- 将重载函数名赋值给函数指针时
- 根据重载规则挑选与函数指针参数列表一致的候选者
- 严格匹配候选者的函数类型与函数指针的函数类型
- 将重载函数名赋值给函数指针时
编程实验:函数重载 VS 函数指针
#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
注意:
- 函数重载必然发生在同一个作用域中
- 编译器需要用参数列表或函数类型进行函数选择
- 无法直接通过函数名得到重载函数的入口地址
二、C++和C相互调用
实际工程中C++和C代码相互调用是不可避免的
C++编译器能够兼容C语言的编译方式
C++编译器会优先使用C++编译的方式
extern
关键字能强制让C++编译器进行C方式的编译extern "C"{ // do C-style compilation here }
编程实验:C++调用C函数
如何保证一段C代码只会以C的方式被编译?
扫描二维码关注公众号,回复:
4471576 查看本文章
文件一:add.c
#include "add.h"
int add(int a, int b)
{
return a + b;
}
文件二:add.h
int add(int a, int b);
文件三:main.cpp
#include <stdio.h>
#ifdef __cplusplus //特殊
extern "C" {
#endif
#include "add.h"
#ifdef __cplusplus
}
#endif
int main()
{
int c = add(1, 2);
printf("c = %d\n", c);
return 0;
}
解决方案:
__cplusplus
是C++编译器内置的标准宏定义__cplusplus
的意义- 确保C代码以统一的C方式被编译成目标文件
#ifdef __cplusplus extern "C" { #endif //C-Style Compilation #ifdef __cplusplus } #endif
注意事项:
- C++编译器不能以C的方式编译重载函数
- 编译方式决定函数名被编译后的目标名
- C++编译方式将函数名和参数列表编译成目标名
- C编译方式只将函数名作为目标名进行编译
三、总结
- 函数重载是C++对C的一个重要升级
- 函数重载通过函数参数列表区分不同的同名函数
extern
关键字能够实现C和C++的相互调用- 编译方式决定符号表中的函数名的最终目标名