绑定成员函数的正确方法?
Correct way to bind member functions?
我有以下代码:
#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(&functionName, param1, param2)
绑定非成员函数,但在函数内部这不再有效,使用 std::bind(&Class::ClassMemberFunctionName, this)
给我留下 unresolved externals
错误:
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Thing::Thing(void)" (??0Thing@@QAE@XZ) referenced in function _main
Error 2 error LNK1120: 1 unresolved externals
绑定此 class 函数的正确方法是什么?
您缺少 Thing::Thing()
构造函数的实现。
我有以下代码:
#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(&functionName, param1, param2)
绑定非成员函数,但在函数内部这不再有效,使用 std::bind(&Class::ClassMemberFunctionName, this)
给我留下 unresolved externals
错误:
Error 1 error LNK2019: unresolved external symbol "public: __thiscall Thing::Thing(void)" (??0Thing@@QAE@XZ) referenced in function _main
Error 2 error LNK1120: 1 unresolved externals
绑定此 class 函数的正确方法是什么?
您缺少 Thing::Thing()
构造函数的实现。