私有成员函数,它采用指向同一类中私有成员的指针
我该怎么做? (以下代码不起作用,但我希望它解释了这个想法。)
class MyClass
{
....
private:
int ToBeCalled(int a, char* b);
typedef (MyClass::*FuncSig)(int a, char* b);
int Caller(FuncSig *func, char* some_string);
}
我想以某种方式调用调用者,例如:
Caller(ToBeCalled, "stuff")
并让 Caller
使用它的任何参数调用 ToBeCalled
感觉需要通过。如果可能的话,我想将所有内容都封装在类的私有部分中。实际上,我有大约 50 个像 ToBeCalled
这样的函数,所以我找不到避免这种情况的方法。
感谢您的任何建议。 :)
How can I do this? (The following code does NOT work, but I hope it explains the idea.)
class MyClass
{
....
private:
int ToBeCalled(int a, char* b);
typedef (MyClass::*FuncSig)(int a, char* b);
int Caller(FuncSig *func, char* some_string);
}
I want to call Caller in some way like:
Caller(ToBeCalled, "stuff")
and have Caller
call ToBeCalled
with whatever parameters it feels needs passing. If at all possible I want to keep everything encapsulated in the private part of my class. In reality, I'd have about 50 functions like ToBeCalled
, so I can't see a way to avoid this.
Thanks for any suggestions. :)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你大部分时间都到了那里。您缺少 typedef 的返回类型,它应该是
现在,您只需要正确使用它:
您想要传递普通的
FuncSig
实例,而不是FuncSig*
--FuncSig*
是一个指向成员函数的指针,具有额外的不必要的间接级别。然后,您可以使用箭头星号运算符(不是其正式名称)来调用它:对于非指针对象(例如堆栈上的对象,或对对象的引用),您可以使用点星号运算符:
另外,请注意运算符优先级——箭头星形和点星形运算符的优先级低于函数调用,因此您需要像我上面所做的那样放入额外的括号。
You're most of the way there. You're missing the return type from the typedef, it should be
Now, you just need to use it properly:
You want to pass around plain
FuncSig
instances, notFuncSig*
-- aFuncSig*
is a pointer to a pointer to a member function, with an extra unnecessary level of indirection. You then use the arrow-star operator (not its official name) to call it:For non-pointer objects (e.g. objects on the stack, or references to objects), you use the dot-star operator:
Also, be wary of operator precedence -- the arrow-star and dot-star operators have lower precedence than function calls, so you need to put in the extra parentheses as I have done above.
我假设您已经尝试过 Caller(MyClass::ToBeCalled, "stuff"),但是您需要函数指针有什么特殊原因吗?另外,请发布实际的编译器错误。
I'm assuming you tried
Caller(MyClass::ToBeCalled, "stuff")
already, but is there any particular reason you need a function pointer? Also, please post the actual compiler error.