函数指针

下文主要讲述函数指针,为了防止与指针函数区分,首先理解两句话。
第一:指针函数是函数,其返回值为指针。
第二:函数指针是指针,是一种指针类型。

  • 1.函数指针的基础知识
    函数指针的声明、定义和使用如代码部分所示:
    首先明确:函数指针是一种指向函数的指针,类比int类型的指针进行理解。
    自然语言的表述:整型指针p_int的声明为:int * p_int; 函数指针 p_func的声明为: 函数* p_func.
    似乎具体的声明如下:指向函数 void func() 的指针为: void func() p_func, **但C++语法规定为 void (p_func)();可以理解为 func 被替换为 (p_func)**
    **因此可以将void (
    )() 等价为 int ,来进行理解函数指针;*
点击查看代码
#include<iostream>

using namespace std;
//函数func
void func() {
    cout << "函数 func()" << endl;
}
//函数指针变量func_ptr,指向函数类型为func
void (*func_ptr)();
//函数指针类型FUNC_PTR, 指向函数func()的
typedef void (*FUNC_PTR)();

int main() {
    //第一种函数调用
    func();
    //第二种函数调用,使用函数指针变量 func_ptr
    func_ptr = func;
    func_ptr();
    (*func_ptr)();
    //同时声明与初始化函数指针变量
    void (*func_ptr2)() = func;
    func_ptr2();
    //第三种函数调用,使用函数指针变量 ptr
    FUNC_PTR ptr = func;
    ptr();

    return 0;
}
  • 2.函数指针的使用
    2.1 作为变量
    2.2 作为函数参数
    2.2 作为函数返回值
点击查看代码
#include<iostream>

using namespace std;
//函数func
void func() {
    cout << "函数 func()" << endl;
}
//函数指针变量func_ptr,指向函数类型为func
void (*func_ptr)();
//函数指针类型FUNC_PTR, 指向函数func()的
typedef void (*FUNC_PTR)();
// 作为函数参数,version 1
void Use_func (string userName, FUNC_PTR myfunc) {
        cout << userName << " 使用";
        myfunc();
}

// 作为函数参数,version 2
void Use_func2 (string userName, void (*myfunc)() ) {
        cout << userName << " 使用";
        myfunc();
}
// 作为函数返回值,version 1
FUNC_PTR Return_func (string userName, FUNC_PTR myfunc) {
        cout << userName << " 使用";
        return myfunc;
}
// 作为函数返回值,version 2
void (* Return_func2 (string userName, FUNC_PTR myfunc) )() {
        cout << userName << " 使用";
        return myfunc;
}
int main() {
    //作为变量:使用函数指针变量 ptr
    FUNC_PTR ptr = func;
    ptr();
    //作为函数参数:
    Use_func("jren", func);
    Use_func2("jren", func);
    //作为函数返回值:
    Return_func("jren", func)();
    Return_func2("jren", func)();
    
    return 0;
}
* 3.函数指针的进阶理解 **void (* )() 等价于 int** 比如数组:int arr[4]; void(*arr[4])();
点击查看代码
#include<iostream>

using namespace std;
//函数func
void func() {
    cout << "函数 func()" << endl;
}
//函数指针变量func_ptr,指向函数类型为func
void (*func_ptr)();
//函数指针类型FUNC_PTR, 指向函数func()的
typedef void (*FUNC_PTR)();

int main() {

    int* arr[4];
    int a0 = 10;
    arr[0] = &a0;

    void(*arr2[4])();
    arr2[0] = func;
    //
    arr2[0]();
    //
    (*arr2[0])();
    FUNC_PTR arr3[4];
    arr3[0] = func;
    //
    arr3[0]();
    //
    (*arr3[0])();


    return 0;
}
posted @ 2022-06-18 02:05  locker_10086  阅读(138)  评论(0编辑  收藏  举报