gpt4 book ai didi

c++ - 是否可以将函数(指针?)保存到对象中?

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:52:56 25 4
gpt4 key购买 nike

我搜索过这个,但我认为我只是让自己更加困惑。

我想要做的是将函数指针保存在一个对象中,稍后在另一个线程中调用它。

我一直在设想的是一个构造函数,它将采用一个函数指针和将传递给该函数指针的参数。该对象还将有一个运行所述函数指针的 run() 方法和一个阻塞直到函数运行的 wait_until_completed() 方法。

如果有意义的话,函数指针应该是来自另一个对象的函数。例如

Foo::*Bar(int);

我的 wait_until_completed() 使用 pthread_cond_t 工作,但我被这个函数指针问题困住了,感觉我只是在原地转圈。

有什么建议吗?

编辑:这是针对学校的(任何我的一般理解)所以第三方图书馆不会工作:/

我觉得我解释得很糟糕,让我给出一些示例代码(不包括所有同步的东西)

class Foo
{
public:
Foo(void (Bar::*function) (int), int function_param)
{
// Save the function pointer into this object
this->function = &function;

// Save the paramater to be passed to the function pointer in this object
param = function_param;
}

run()
{
(*function)(param);
}

private:
// The function pointer
void (Bar::*function) (int) = NULL;

// The paramater to pass the function pointer
int param;
}

简而言之,这就是我正在尝试做的事情。但是,我不确定这是语法问题还是我太蠢了,但我不知道如何实际执行此操作并使其编译。

虽然?并感谢到目前为止的所有建议 :)

最佳答案

首先,您需要typedef 您的函数类型,以便更容易重用它并减少潜在的错误。

typedef void (Bar::*function_type)(int);

现在您可以像这样使用 typedef 了:

Foo(function_type func, int func_param)
: function_(func)
, param_(func_param)
{
}

此外,使用初始化列表来初始化成员变量是个好主意(您可以找到有关初始化列表的更多信息 here)。
但是,您仍然无法调用该函数。类成员函数,也称为绑定(bind)函数,必须与实例化对象一起使用,因为它们绑定(bind)到它们。您的 run 函数必须如下所示(您还忘记了返回类型):

void run(Bar* object){
(object->*function_(param_));
}

它使用特殊的->*运算符通过成员函数指针调用成员函数。
此外,您不能直接在类内初始化大多数变量(只能初始化静态积分常量,如 static const int i = 5;)。现在您可以实例化一个 Foo 对象并在其上调用运行函数。
这里有一个完全可编译的示例:

#include <iostream>
using namespace std;

class Bar{
public:
void MyBarFunction(int i){
cout << i << endl;
}
};

class Foo
{
public:
typedef void (Bar::*function_type)(int);

Foo(Bar* object, function_type function, int function_param)
: object_(object) // save the object on which to call the function later on
, function_(function) // save the function pointer
, param_(function_param) // save the parameter passed at the function
{
}


void Run()
{
(object_->*function_)(param_);
}

private:
// The object to call the function on
Bar* object_;

// The function pointer
function_type function_;

// The paramater to pass the function pointer
int param_;
};

int main(void){
// create a Bar object
Bar bar;
// create a Foo object, passing the Bar object
// and the Bar::myBarFunction as a parameter
Foo foo(&bar, &Bar::MyBarFunction, 5);

// call Bar::MyBarFunction on the previously passed Bar object 'bar'
foo.Run();

cin.get();
return 0;
}

这可能有点难以理解,但我希望这能帮助您理解成员函数指针以及如何使用它们。 :)

关于c++ - 是否可以将函数(指针?)保存到对象中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4880308/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com