函数指针学习(还没明白具体含义难点)

来源:互联网 发布:湄公河惨案 知乎 编辑:程序博客网 时间:2024/05/19 12:16

#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include "test.h"
using namespace std;


//*********************************************************************************
//FUNCTION:
void print()
{
 cout << "print is called!" << endl;
}

void fun()
{
 cout << "fun is called!" << endl;
}

static void (* _malloc_alloc_oom_handle)() = NULL;
static void (* set_malloc_handle(void (*f)()))() //必须返回一个void _fun(void) 的函数指针, 或者根本不返回
{
 void (* old)() = _malloc_alloc_oom_handle;
 _malloc_alloc_oom_handle = f;
 return (old);
}
//*********************************************************************************
//FUNCTION:
void putString(char *p)
{
 if (NULL == p)
 {
  cout << "putString is called!" << endl;
  return ;
 }
 cout << p << endl;
}

void hellow(char *p)
{
 if (NULL == p)
 {
  cout << "hellow word!" << endl;
  return ;
 }
 cout << p << endl;
}

static void (* _malloc_alloc_oom_handle_p)(char *p) = NULL;
static void (* set_malloc_handle(void (*f)(char *p)))(char *p)
{//这个函数的参数为一个函数指针(这个函数指针指一个参数为char*且返回值为空的函数);这个函数返回一个函数指针,这个函数指针指一个参数为char*且返回值为空的函数。
 void (* old)(char *pp) = _malloc_alloc_oom_handle_p;
 _malloc_alloc_oom_handle_p = f;
 return (old);
}
//*********************************************************************************
//FUNCTION:
int add(int x, int y)
{
 cout << "add is called!" << endl;
 return x + y;
}

int sub(int x, int y)
{
 cout << "sub is called!" << endl;
 return x - y;
}

static int (* _malloc_alloc_oom_handle_int)(int x, int y) = NULL;
static int (* set_malloc_handle(int (*f)(int x, int y)))(int x, int y)
{
 int (* old)(int xx, int yy) = _malloc_alloc_oom_handle_int;
 _malloc_alloc_oom_handle_int = f;
 return old; //这句话去掉也是可行的
 //return 1; //报错
}

 

int main()
{
 _malloc_alloc_oom_handle = print;
    void (* old)() = set_malloc_handle(fun);
 _malloc_alloc_oom_handle();
 old();

 _malloc_alloc_oom_handle_p = putString;
 void (*oldp)(char *p) = set_malloc_handle(hellow);
 _malloc_alloc_oom_handle_p("wyp wyp");
 oldp(NULL);

 _malloc_alloc_oom_handle_int = add;
 int (* oldint)(int x, int y) = set_malloc_handle(sub);
 int reslut;
 reslut = _malloc_alloc_oom_handle_int(10 , 10);
 cout << reslut << endl;
 reslut = oldint(10, 10);
 cout << reslut << endl;

 system("pause");
 return 0;
}