C++ 结构指针函数指向其他结构的其他函数
我想知道是否有可能将其他结构的功能指向一个结构的功能: 例如:C++ 结构指针函数指向其他结构的其他函数,c++,struct,c++14,function-pointers,C++,Struct,C++14,Function Pointers,我想知道是否有可能将其他结构的功能指向一个结构的功能: 例如: 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; }
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;
}
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;
}
这在结构中是可能的?函数的声明应该如下所示:
int(sta::*func)(int);
或者,或者:
using my_type = int(sta::*)(int);
my_type func;
这更容易理解:my_type
是指向sta
的成员函数的类型指针的别名,该函数获取int
并返回int
func
只不过是具有类型my\u type
的数据成员
要将指向成员函数的实际指针指定给func
,可以执行以下操作:
sah.func = &sta::func;
然后可以按如下方式调用它:
(sa.*sah.func)(0);
指向方法的指针的正确语法为:
&T::f
其中T
是声明方法f
的类型。请注意,要调用,指针必须绑定到T
的实例,因为指针的值表示到内存中实例开头的偏移量
<>在C++ 14中,可以考虑<代码> STD::函数< /> >:
#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;
}
请参阅,并在cppreference.com上。尝试了一次又一次之后,解决方案是这样的:
int(sta::*func)(int);
例如:
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;
}
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;
}
typedef结构
{
INTA;
int-SomeFunc(int-a)
{
返回a*4;
}
}索姆斯特;
类型定义结构
{
INTA;
内部(*HGetValX)(内部);
}hst;
int main()
{
hst*a;
hst decfunc;//新实例
索姆斯特b;
decfunc.HGetValX=(int(*)(int))0x421C10;//内存地址,或&b.SomeFunc;|&b.SomeFunc;生成警告。
b、 a=20;
a=(hst*)和b;
在你的例子中,你不能使用一个匿名的结构,因为你给了他们name@DenisSheremet我的错。可能的解决方案问题是sta是虚构的,内存地址如何?有任何形式吗?@nikomastersta
在您的示例中是一个定义良好的类。它意味着什么是虚构的?我指的是逆向工程,例如示例:@nikomaster否,如果要使用指向函数的指针而不是指向成员函数的指针,则必须将成员方法定义为static
。例如,请参阅。