私有成员函数接受指向同一类中的私有成员的指针 [英] Private member function that takes a pointer to a private member in the same class
问题描述
我该如何做? (下面的代码不工作,但我希望它解释了这个想法。)
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);
}
我想以某种方式呼叫Caller:
I want to call Caller in some way like:
Caller(ToBeCalled, "stuff")
并拥有 Caller
调用 ToBeCalled
。如果可能,我想保持一切封装在我的类的私有部分。实际上,我有大约50个函数,比如 ToBeCalled
,所以我找不到一种避免这种情况的方法。
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. :)
推荐答案
你大部分都在那里。你缺少来自typedef的返回类型,应该是
You're most of the way there. You're missing the return type from the typedef, it should be
typedef int (MyClass::*FuncSig)(int, char*);
现在,您只需要正确使用它:
Now, you just need to use it properly:
int Caller(FuncSig func, int a, char* some_string)
{
return (this->*func)(a, some_string);
}
您要传递简单 FuncSig
实例,而不是 FuncSig *
- a FuncSig *
是指向成员函数的指针,具有额外的不必要的间接级别。然后使用arrow-star运算符(而不是其官方名称)来调用它:
You want to pass around plain FuncSig
instances, not FuncSig*
-- a FuncSig*
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:
(object_to_be_called_on ->* func)(args);
对于非指针对象(例如堆栈上的对象或对象的引用)点星号运算符:
For non-pointer objects (e.g. objects on the stack, or references to objects), you use the dot-star operator:
MyClass x;
(x .* func)(args);
此外,请注意运算符优先级 - 箭头星号和点星号运算符的优先级较低比函数调用,所以你需要放入额外的括号,如我上面做的。
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.
这篇关于私有成员函数接受指向同一类中的私有成员的指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!