首页
社区
课程
招聘
[原创]C++类成员指针调用
2022-1-25 17:21 3765

[原创]C++类成员指针调用

2022-1-25 17:21
3765
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <iostream>
 
template<typename dst_type, typename src_type>
dst_type pointer_cast(src_type src)
{
    return *static_cast<dst_type*>(static_cast<void*>(&src));
}
 
class aa;
typedef int (aa::*pfun)(int);
 
class aa
{
public:
    aa()
    {
 
    }
    int push(void* f)
    {
        m_fun = f;
        return 0;
    }
    int afun(int a)
    {
        pfun f = pointer_cast<pfun>(m_fun);
        return (this->*f)(a);
    }
public:
    void* m_fun;
 
};
 
class bb : public aa
{
 
public:
    int bfun(int a)
    {
        printf("%d\n", a);
        return 0;
    }
 
};
 
int main()
{
    bb b;
    b.push(pointer_cast<void*>(&bb::bfun));
 
    aa* a = &b;
    a->afun(5);
 
    return 0;
}

阿里云助力开发者!2核2G 3M带宽不限流量!6.18限时价,开 发者可享99元/年,续费同价!

收藏
点赞1
打赏
分享
最新回复 (0)
游客
登录 | 注册 方可回帖
返回