boost::function<void()> test_func;
struct test_t
{
boost::function<void(int)> foo_;
void test()
{
// This works as expected
test_func = boost::bind(test_t::foo_, 1);
}
};
int main(int argc, _TCHAR* argv[])
{
test_t test;
test.test();
// error C2597: illegal reference to non-static member 'test_t::foo_'
test_func = boost::bind(test_t::foo_, &test, 1);
const auto a = 0;
return 0;
}
代码有什么问题?为什么代码test_func = boost::bind(test_t::foo_, &test, 1);在test_t::test()中编译并在main()中给出错误?
谢谢
这是因为在一个方法内部,test_t::foo_
引用this->foo_
,而main
中的test_t::foo_
只有在它是该类的静态成员时才能引用foo_
。你需要在这里写test.foo_
问题或多或少是错误所说的。test_t::foo_
不是函数;它是一个函子(函数对象),它不是静态的。因此,如果没有test_t
对象,就不能访问它。试试这个:
test_func = boost::bind(test.foo_, 1);