文章标题 C与C++的函数指针

//---------------函数指针 :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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值