结构指针功能指向其他结构的其他功能 [英] struct pointer function points to other function of other struct

查看:80
本文介绍了结构指针功能指向其他结构的其他功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以将其他结构的函数指向一个结构:

I was wondering if is possible to point a function of other structure into of a structure:

示例:

typedef struct
{
    int func(int z)
    {
        return z * 2;
    }
} sta;

typedef struct
{
    int(*this.func)(int);
} stah;


int main()
{
    sta sa;
    stah sah;

    sah.func = &sa.func;

    return 0;
}

是否可能在结构中?

推荐答案

func 的声明应如下所示:

int(sta::*func)(int);

或者,或者:

using my_type = int(sta::*)(int);
my_type func;

这更容易阅读: my_type 是类型指向 sta 成员函数的指针的别名,该成员函数获取 int 并返回 int

func 仅仅是类型为<$ c的数据成员$ c> my_type 。

This is easier to read: my_type is an alias for the type pointer to a member function of sta that gets an int and returns an int.
func is nothing more that a data member having type my_type.

为了将指向成员函数的实际指针分配给 func ,您可以改为:

In order to assign an actual pointer to member function to func, you can do this instead:

sah.func = &sta::func;

然后可以按如下所示调用它:

You can then invoke it as it follows:

(sa.*sah.func)(0);

这篇关于结构指针功能指向其他结构的其他功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆