C++函数指针

 1 // CallBack.cpp : 定义控制台应用程序的入口点。
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <stdio.h>
 6 #include <string>
 7 #include <iostream>
 8 
 9 using namespace std;
10 
11 typedef struct
12 {
13     void(*strPf)(string str);
14     void(*hexPf)(uint8_t hex);
15     void(*intPf)(int a, int b, int c);
16 }CallBack;
17 
18 void strCall(string str)
19 {
20     cout << str << endl;
21 }
22 
23 void hexCall(uint8_t hex)
24 {
25     printf("%o  %d   %x ", hex, hex, hex);
26     cout << endl;
27 }
28 
29 void intCall(int a, int b, int c)
30 {
31     cout << "a:" << a << "b:" << b << "c:" << c << endl;
32 }
33 
34 void test(CallBack * fun)
35 {
36     fun->strPf("hello world");
37     fun->hexPf(0xC3);
38     fun->intPf(333, 666, 999);
39 }
40 
41 uint16_t bytesToInt(uint16_t * pbt)
42 {
43     int a = *(pbt) << 8;
44     a |= *(pbt + 1);
45     return a;
46 }
47 
48 int main()
49 {
50     CallBack fun;
51 
52     uint16_t data[2] = { 0x05, 0x00 };
53 
54     fun.strPf = strCall;
55     fun.hexPf = hexCall;
56     fun.intPf = intCall;
57 
58     test(&fun);
59 
60     cout << bytesToInt(data) << endl;
61     
62     getchar();
63     return 0;
64 }
posted @ 2020-01-10 17:13  Yan327  阅读(140)  评论(0编辑  收藏  举报