c++将一个类的回调函数注入到另一个类中的方法

简介: c++将一个类的回调函数注入到另一个类中的方法

代码如下:

#pragma once
#include <iostream>
//字节对齐
#ifdef __GNUC__
#define SNFTK_PACKED(...) __VA_ARGS__ __attribute__((__packed__))
#elif _MSC_VER
#define SNFTK_PACKED(...) __pragma(pack(push, 1)) __VA_ARGS__ __pragma(pack(pop))
#else
#error Unknown compiler
#endif
typedef void(*callbackFunc1) ();
typedef void(*callbackFunc2) (float a, float b);
typedef void(*callbackFunc3) (int a, float b);
SNFTK_PACKED(typedef struct
{
  callbackFunc1 TestFunc1;
  callbackFunc2 TestFunc2;
  callbackFunc3 TestFunc3;
} callBackFuncs);
//将Test3类中的回调函数注入到Test2中
class Test2
{
public:
  static Test2& GetInstance() { static Test2 t; return t; }
  void init(void* ptr) { cbfs = (callBackFuncs*)ptr; }
  callBackFuncs* GetCallBackFuncs() { return cbfs; }
private:
  callBackFuncs* cbfs;
};
class Test3
{
public:
  void test1() { std::cout << "321" << std::endl; }
  void test2(float a, float b) { std::cout << "654" << std::endl; }
  void test3(int a, float b) { std::cout << "987" << std::endl; }
  void init()
  {
    callBackFuncs callBacks = { 0 };
    callBacks.TestFunc1 = &(Test3::test1);
    callBacks.TestFunc2 = &(Test3::test2);
    callBacks.TestFunc3 = (Test3::test3);
    Test2 t2 = Test2::GetInstance();
    t2.init((void*)(&callBacks));
  }
};
void demo()
{
}
int main()
{
  while (1);
  return 0;
}
相关文章
|
5天前
|
存储 编译器 C语言
c++的学习之路:5、类和对象(1)
c++的学习之路:5、类和对象(1)
19 0
|
5天前
|
C++
c++的学习之路:7、类和对象(3)
c++的学习之路:7、类和对象(3)
19 0
|
3天前
|
设计模式 Java C++
【C++高阶(八)】单例模式&特殊类的设计
【C++高阶(八)】单例模式&特殊类的设计
|
4天前
|
编译器 C++
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
【C++基础(八)】类和对象(下)--初始化列表,友元,匿名对象
|
8天前
|
存储 安全 C语言
【C++】string类
【C++】string类
|
存储 编译器 Linux
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
标准库中的string类(中)+仅仅反转字母+字符串中的第一个唯一字符+字符串相加——“C++”“Leetcode每日一题”
|
10天前
|
编译器 C++
标准库中的string类(上)——“C++”
标准库中的string类(上)——“C++”
|
10天前
|
编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(中)——“C++”
|
10天前
|
存储 编译器 C++
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
自从学了C++之后,小雅兰就有对象了!!!(类与对象)(上)——“C++”
|
11天前
|
C++
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元
【C++成长记】C++入门 | 类和对象(下) |Static成员、 友元