栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

一般函数指针和类的成员函数指针深入解析

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

一般函数指针和类的成员函数指针深入解析

函数指针是通过指向函数的指针间接调用函数。函数指针可以实现对参数类型、参数顺序、返回值都相同的函数进行封装,是多态的一种实现方式。由于类的非静态成员函数中有一个隐形的this指针,因此,类的成员函数的指针和一般函数的指针的表现形式不一样。

1、指向一般函数的指针
函数指针的声明中就包括了函数的参数类型、顺序和返回值,只能把相匹配的函数地址赋值给函数指针。为了封装同类型的函数,可以把函数指针作为通用接口函数的参数,并通过函数指针来间接调用所封装的函数。
下面是一个指向函数的指针使用的例子。
复制代码 代码如下:
#include

typedef int (*pFun)(int, int);
int Max(int a, int b)
{
    return a > b ? a : b;
}
int Min(int a, int b)
{
    return a < b ? a : b;
}

int Result(pFun fun, int a, int b)
{
    return (*fun)(a, b);
}
void main()
{
    int a = 3;
    int b = 4;
    cout<<"Test function pointer: "<    cout<<"The maximum number between a and b is "<    cout<<"The minimum number between a and b is "<}

2、指向类的成员函数的指针
类的静态成员函数采用与一般函数指针相同的调用方式,而受this指针的影响,类的非静态成员函数与一般函数指针是不兼容的。而且,不同类的this指针是不一样的,因此,指向不同类的非静态成员函数的指针也是不兼容的。指向类的非静态成员函数的指针,在声明时就需要添加类名。

下面是一个指向类的成员函数的指针的使用的例子,包括指向静态和非静态成员函数的指针的使用。
复制代码 代码如下:
#include

    class CA;

   
    typedef int (CA::*pClassFun)(int, int);

   
    typedef int (*pGeneralFun)(int, int);

    class CA
    {
    public:

        int Max(int a, int b)
        {
            return a > b ? a : b;
        }

        int Min(int a, int b)
        {
            return a < b ? a : b;
        }

        static int Sum(int a, int b)
        {
            return a + b;
        }

       
        int Result(pClassFun fun, int a, int b)
        {
            return (this->*fun)(a, b);
        }

    };

   
    int Result(CA* pA, pClassFun fun, int a, int b)
    {
        return (pA->*fun)(a, b);
    }

   
    int GeneralResult(pGeneralFun fun, int a, int b)
    {
        return (*fun)(a, b);
    }

   
    void main()
    {
        CA ca;
        int a = 3;
        int b = 4;

        cout<<"Test nonstatic member function pointer from member function:"<        cout<<"The maximum number between a and b is "<        cout<<"The minimum number between a and b is "<
        cout<        cout<<"Test nonstatic member function pointer from external function:"<        cout<<"The maximum number between a and b is "<        cout<<"The minimum number between a and b is "<
        cout<        cout<<"Test static member function pointer: "<        cout<<"The sum of a and b is "<    }

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/66289.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号