//---------------函数指针 :C
//定义—— 返回类型 (* 函数指针名称)(参数类型,参数类型...)
#include <iostream>
using namespace std;
void fun1()
{
printf("fun1 called.\n");
}
void fun2(char c)
{
printf("fun2 called :%c\n", c);
}
int mainC()
{
void(*pfun1)() = NULL;//先初始化,——安全!
void(*pfun2)(char) = NULL;
pfun1 = fun1;//函数指针第一种赋值方法
pfun2 = &fun2;//函数指针第二种赋值方法
if (pfun1 != NULL)
{
(*pfun1)();//函数指针调用第一种方法
pfun1();//函数指针调用第二种方法
}
if (pfun2 != NULL)
{
pfun2('a');
(*pfun2)('A');
}
return 0;
}
//---------------函数指针 :C++
//定义—— 返回类型 (类名::* 函数指针名称)(参数类型,参数类型...)
//------------------静态成员函数与C一样
#include <iostream>
using namespace std;
class Yechao
{
public:
int fun1()
{
cout << "Yechao::fun1() called\n";
return 1;
}
int fun2(char c)const
{
cout << "Yechao::fun2() called\n";
return 1;
}
static void fun3(char* p_ch);
virtual void vfun4(char c)
{
cout << "Yechao::vfun4 called"<< c << "\n";
}
virtual void vfun5(char c)
{
cout << "Yechao::vfun5 called" << c << "\n";
}
virtual void vfun6(char c)
{
cout << "Yechao::vfun6 called" << c << "\n";
}
};
void Yechao::fun3(char* p_ch)
{
cout << "Ychao::fun3() called->" << p_ch << "\n";
}
int mainCPP()
{
//静态成员函数——如同C
void(*pfun3)(char*) = NULL;
pfun3 = Yechao::fun3;//函数指针第一种赋值
if (pfun3 != NULL)
{
pfun3("Yechao");
(*pfun3)("Yechao");
}
pfun3 = NULL;
pfun3 = &Yechao::fun3;//函数指针第二种赋值
if (pfun3 != NULL)
{
pfun3("Yechao");//函数指针调用第一种方法
(*pfun3)("Yechao");//函数指针调用第二种方法
}
Yechao ye;//构造对象
//普通成员函数
int(Yechao::*pfun1)() = NULL;
pfun1 = &Yechao::fun1;//一定要加&
(ye.*pfun1)();//调用方式——(对象.*函数指针)(参数)
//const 函数(基本普通成员函数相同)
int(Yechao::*pfun2)(char)const = NULL; //const 不能忘
pfun2 = &Yechao::fun2;
(ye.*pfun2)('A');
//虚函数的调用
typedef void(__stdcall *pvfun)(char);
pvfun pvirtualFun;
pvirtualFun = (pvfun)*( (int*)(*(int*)(&ye)) + 0 );//(int*)(*(int*)(&ye))虚函数表的表头指针
pvirtualFun('3');
pvirtualFun = (pvfun)*((int*)(*(int*)(&ye)) + 1);//(int*)(*(int*)(&ye))虚函数表的表头指针
pvirtualFun('3');
pvirtualFun = (pvfun)*((int*)(*(int*)(&ye)) + 2);//(int*)(*(int*)(&ye))虚函数表的表头指针
pvirtualFun('3');
return 0;
}
int main()
{
mainC();
mainCPP();
//构造函数或者析构函数的指针,貌似不可以,不知道c++标准有没有规定不能有指向这两者的函数指针
return 0;
}
文章标题 C与C++的函数指针
最新推荐文章于 2023-03-15 14:46:51 发布