【问题标题】:Correct way to bind member functions?绑定成员函数的正确方法?
【发布时间】:2015-03-09 07:53:48
【问题描述】:

我有以下代码:

#include <iostream>
#include <vector>
#include <functional>

using namespace std;
using namespace std::placeholders;

typedef std::vector<std::function<void(void)>> func_list;

class Thing {
private:
    func_list flist;
    void _sayHi() {
        cout << "hi" << endl;
    }
    void _sayNum(int num) {
        cout << num << endl;
    }
public:
    Thing();
    void sayHi();
    void sayNum(int num);
    void executeFunctions();
};

void Thing::sayHi() {
    flist.push_back(
        std::bind(&Thing::_sayHi, this)  //  Unsure of the correct usage here
    );
}

void Thing::sayNum(int num) {
    flist.push_back(
        std::bind(&Thing::_sayNum, this, num)  //  Unsure of the correct usage here
    );
}

void Thing::executeFunctions() {
    for (unsigned int i = 0; i < flist.size(); i++) {
        flist.at(i)();
    }
}

int main() {
    Thing thing = Thing();
    thing.sayHi();
    thing.sayNum(5);

    thing.executeFunctions();
}

我的目标只是在调用函数时存储它们,以便以后执行它们。我可以使用 std::bind(&amp;functionName, param1, param2) 绑定非成员函数,但在函数内部这不再有效,使用 std::bind(&amp;Class::ClassMemberFunctionName, this) 会给我留下 unresolved externals 错误:

错误 1 ​​错误 LNK2019:函数 _main 中引用的未解析外部符号“public: __thiscall Thing::Thing(void)”(??0Thing@@QAE@XZ)

错误 2 错误 LNK1120: 1 未解决的外部

绑定此类函数的正确方法是什么?

【问题讨论】:

    标签: c++ function bind member-functions


    【解决方案1】:

    您缺少Thing::Thing() 构造函数的实现。

    【讨论】:

    • 请注意,这里的解决方案似乎是删除声明,而不是添加定义,因为类中没有任何内容需要显式初始化。
    猜你喜欢
    • 2019-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-07
    • 1970-01-01
    • 2018-07-30
    • 1970-01-01
    相关资源
    最近更新 更多