【问题标题】:Function struct points to other function of other struct [duplicate]函数结构指向其他结构的其他功能[重复]
【发布时间】:2016-10-21 04:23:56
【问题描述】:

我试图将一个结构函数指向另一个结构的另一个函数,

请考虑一下:

// Main Structure:

typedef struct
{
    int GetValA(int a)
    {
        return a * 2;
    }
} x;


typedef struct
{
    int(*HGetValA)(int); // Pointer function    
} hookx;

// Then

int main()
{
    x v1;

    hookx* v2;

    v2 = (hookx*)&v1; // or 0x0 memory address

    // Now declaring pointer function

    v2->HGetValA = (int(*)(int))&v1.GetValA; // Pointing to function of the main structure.
}

对我来说,这看起来不错,但在编译时给了我错误:

[警告] 从 'int (x::)(int)' 转换为 'int ()(int)' [-Wpmf-conversions]

【问题讨论】:

    标签: c++ pointers struct c++14 memory-address


    【解决方案1】:

    指向类/结构成员的指针并不真正意味着地址,它只是指向this 的偏移量。

    因此类/结构外的指针类型(如您的代码中的int ()(int))与内部(如int (::)(int))不同。

    您必须使用看起来是范围的类/结构名称来声明指针(确实如此)。

    【讨论】:

    • 没有名字就不可能吗?
    • 在这个程序中在GetValA()之前添加一个关键字static是有效的。但也许这不是你写的确切内容。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多