草庐IT

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

coder 2024-02-06 原文

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

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

我一直在设想的是一个构造函数,它将采用一个函数指针和将传递给该函数指针的参数。该对象还将有一个运行所述函数指针的 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/

有关c++ - 是否可以将函数(指针?)保存到对象中?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby - 为什么我可以在 Ruby 中使用 Object#send 访问私有(private)/ protected 方法? - 2

    类classAprivatedeffooputs:fooendpublicdefbarputs:barendprivatedefzimputs:zimendprotecteddefdibputs:dibendendA的实例a=A.new测试a.foorescueputs:faila.barrescueputs:faila.zimrescueputs:faila.dibrescueputs:faila.gazrescueputs:fail测试输出failbarfailfailfail.发送测试[:foo,:bar,:zim,:dib,:gaz].each{|m|a.send(m)resc

  3. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  4. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  5. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  6. ruby - 我可以使用 Ruby 从 CSV 中删除列吗? - 2

    查看Ruby的CSV库的文档,我非常确定这是可能且简单的。我只需要使用Ruby删除CSV文件的前三列,但我没有成功运行它。 最佳答案 csv_table=CSV.read(file_path_in,:headers=>true)csv_table.delete("header_name")csv_table.to_csv#=>ThenewCSVinstringformat检查CSV::Table文档:http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV/Table.html

  7. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  8. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  9. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  10. ruby - 检查数组是否在增加 - 2

    这个问题在这里已经有了答案:Checktoseeifanarrayisalreadysorted?(8个答案)关闭9年前。我只是想知道是否有办法检查数组是否在增加?这是我的解决方案,但我正在寻找更漂亮的方法:n=-1@arr.flatten.each{|e|returnfalseife

随机推荐