【发布时间】:2016-03-20 05:02:38
【问题描述】:
我有两个结构体,结构体 B 继承自结构体 A。我想将一个函数作为参数从结构体 B 传递给结构体 A 以供结构体 A 使用。
这是我想要实现的目标和遇到的问题的示例,完整的代码将是 TL;DR。
struct A
{
int32 mynum;
void Tick(float delta, bool doThis, void (funcparam)(float, bool, int32))
{
funcparam(delta, doThis, mynum);
}
};
struct B : public A
{
void RunThis(float deltaTime, bool doIt, int32 which)
{
// do something when called by Struct A
};
void DoSomething()
{
Tick(0.1f, true, &B::RunThis);
};
};
问题在于这一行:Tick(0.1f, true, &B::RunThis); 来自函数 void DoSomething(),除非我从一开始就做错了,但我想我传递错了,因为它仍然在我的结构的标题中m 当前定义?
错误(我已经修改了错误以适合我的示例,我不认为我搞砸了..):
error C2664: 'void A::Tick(float,bool,void (__cdecl *)(float,bool))': cannot convert argument 3 from 'void (__cdecl B::* )(float,bool)' to 'void (__cdecl *)(float,bool)'
从&B::RunThis 中省略B:: 当然不能解决任何问题。
【问题讨论】:
-
查看
std::function(),您的函数指针void (funcparam)(float, bool, int32)无法获取成员函数指针。 -
void (funcparam)(float, bool, int32)不是你想要的。首先,(非成员)函数指针的签名是void (* funcparam) (float, bool, int32)(你错过了*)。其次,您可以使 Tick() 成为基类的函数,然后调用一个虚函数,在派生类中覆盖该虚函数。与使用std:function相比,这仍然是一种更好的方法,只要您具有“派生类”:“您要执行的功能”的 1:1 关系。 -
@BitTickler - 这对我来说是一个更好的解决方案,谢谢!至于具体问题的答案,我还是等贴出来,让google类似问题的人有准确答案
-
@πάνταῥεῖ - 看起来不错,如果你能用一个简短的例子发布答案,我会打勾
标签: c++ struct parameter-passing