C++之函数指针实现函数回调

时间:2021-01-17 18:59:01

1、问题

C++很多地方需要函数指针回调,但是我理解还是不够深刻,今天再写了测试例子,方便后面更深入理解和记忆。


2、代码实现

A.h 文件实现
//
// A.h
// TestC++
//
// Created by 1111 on 17/8/17.
// Copyright © 2017年 sangfor. All rights reserved.
//


#ifndef A_h
#define A_h

#include <iostream>

class A
{

public:
A(void){}
~A(void){}
typedef void(*fun)(int);
typedef void(*fun1)(void*, int);
void callback(fun f, int n)
{
std::cout << "callback before" << std::endl;
f(n);
std::cout << "callback after" << std::endl;
}
void callback1(void *obj, fun1 f1, int n1)
{
object = obj;
f = f1;
n = n1;
}
void exec()
{
std::cout << "callback1 before" << std::endl;
f(object, n);
std::cout << "callback1 before" << std::endl;
}
private:
fun1 f;
void *object;
int n;
};

#endif /* A_h */

main.cpp文件实现
//
// main.cpp
// TestC++
//
// Created by 1111 on 17/3/19.
// Copyright © 2017年 sangfor. All rights reserved.
//

#include <iostream>
#include <string.h>
#include "A.h"

using namespace std;

void printf(int n) {
std::cout << n << std::endl;
}

class B
{
public:
static void fun(void *p, int n)
{
std::cout << "fun" << std::endl;
B *b = (B *)p;
b->test(n);
}

void test(int n)
{
if (n % 2 == 0)
std::cout << n << " % 2 == 0" << std::endl;
else
std::cout << n << " % 2 != 0" << std::endl;
}
void exec()
{
A a;
a.callback1(this, fun, 100);
std::cout << "B exec" << std::endl;
a.exec();
}
};


int main(int argc, const char * argv[]) {
printf("hello\n");
A a;
a.callback(printf, 5);
B b;
b.exec();
//f(get);
return 0;
}






3、结果

hello
callback before
5
callback after
B exec
callback1 before
fun
100 % 2 == 0
callback1 before
Program ended with exit code: 0