如何将对象的方法传递给外部函数 [英] How to pass an object's method to an external function
问题描述
给定一个名为 myObj
的对象,其中包含函数 doThis
和 doThat
,将对象(和指令到函数)传递给外部函数的最好方法是什么?
Given an object named myObj
with functions doThis
and doThat
, what is the best way to pass the object (and the directive to a function) to an external function?
作为我目前做的一个例子,我一个外部函数 void whatToDo(myClass myObj,string myFunction)
其中我简单地传递 doThis
c $ c> doThat 为 myFunction
并检查:
As an example of how I am currently doing this, I an external function void whatToDo( myClass myObj, string myFunction)
where I simply pass in either doThis
or doThat
as myFunction
and check it:
void whatToDo( myClass myObj, string myFunction) {
if( myFunction == "doThis") myObj.doThis();
if( myFunction == "doThat") myObj.doThat();
}
但是,随着类的增长,这变成一个更糟的选择。有没有办法将实际的函数传递给 whatToDo
,以便我可以直接调用它?
However, as the class grows, this becomes a worse and worse option. Is there a way to pass the actual function to whatToDo
so that I can just call it directly?
推荐答案
这是成员函数的指针:
void whatToDo(myClass& myObj, void (myClass::*p)())
{
// p is a pointer to a member function class myClass that
// takes no arguments and returns void
// you can invoke it thusly
(myObj.*p)();
}
您可以提供以下指针:
struct myClass {
void doThis();
void doThat();
};
myClass c;
whatToDo(c, &myClass::doThis); // will invoke c.doThis();
whatToDo(c, &myClass::doThat); // will invoke c.doThat();
这篇关于如何将对象的方法传递给外部函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!