【问题标题】:struct pointer function points to other function of other struct结构指针函数指向其他结构的其他函数
【发布时间】:2016-10-21 09:06:25
【问题描述】:

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

例子:

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;
}

这可能在结构中吗?

【问题讨论】:

  • 在您的示例中,您没有使用匿名结构,因为您给它们命名
  • @DenisSheremet 我的错。
  • Here 是可能的解决方案

标签: c++ struct c++14 function-pointers


【解决方案1】:

func 的声明应如下所示:

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

或者,或者:

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

这更容易阅读:my_type 是类型的别名指向sta 的成员函数的指针,它获取int 并返回int
func 只不过是一个类型为 my_type 的数据成员。

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

sah.func = &sta::func;

然后您可以按如下方式调用它:

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

【讨论】:

  • 问题是 sta 是虚构的,内存地址会是怎样的?
  • 有什么表格吗?
  • @nikomaster sta 在您的示例中是一个定义明确的类。 是虚构的是什么意思??
  • i 表示逆向工程,例如:
  • @nikomaster 不,如果你想使用指向函数的指针而不是指向成员函数的指针,你必须将你的成员方法定义为static。例如,请参阅here
【解决方案2】:

方法指针的正确语法是:

&T::f

其中T 是声明方法f 的类型。请注意,要被调用,指针必须绑定到T 的实例,因为指针的值表示内存中实例开头的偏移量。

在 C++14 中,你可以考虑std::function:

#include <functional>

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

struct stah
{
    std::function<int(int)> func;
};


int main()
{
    sta sa;
    stah sah;

    sah.func = std::bind(&sta::func, &sa, std::placeholders::_1);

    return 0;
}

您也可以使用 lambdas 代替 std::bind

int main()
{
    sta sa;
    stah sah;

    sah.func = [&sa](int z) { return sa.func(z); };

    return 0;
}

请参阅 cppreference.com 上的 std::functionstd::bindstd::placeholders

【讨论】:

    【解决方案3】:

    经过尝试和尝试,解决方案是这样的:

    例子:

    typedef struct 
    {
        int a;
    
        int SomeFunc(int a)
        {
            return a * 4;
        }
    
    } somst;
    
    
    typedef struct
    {
        int a;
        int (*HGetValX)(int);
    } hst;
    
    
    int main()
    {
        hst* a;
        hst decfunc; // New instance
        somst b;
    
        decfunc.HGetValX = (int(*)(int))0x421C10; // memory address, or &b.SomeFunc; | &b.SomeFunc; Produces warnings.
        b.a = 20;
    
        a = (hst*)&b;
    
    
        cout << decfunc.HGetValX(4) << b.SomeFunc(4) << a->a <<  endl;
    
        return 0;
    }
    

    寻找内存地址

    然后代码在没有警告的情况下编译,目标是将结构与它们的功能挂钩。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多