指向成员函数的指针错误

Pointer to member function error

本文关键字:指针 错误 函数 成员      更新时间:2023-10-16

当我编译以下代码时,我收到以下错误。谁能帮我解决这个问题。谢谢。

错误:ISO C++禁止获取绑定成员函数的地址来形成指向成员函数的指针。 说 '&foo::abc' [-fallowive]

boost::thread testThread(boost::bind(&f.abc, f));

......

......

#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
class foo
{
    private:
    public:
    foo(){}
    void abc()
    {
        std::cout << "abc" << std::endl;
    }
};
int main()
{
    foo f;
    boost::thread testThread(&f.abc, f);
    return 0;
}
错误消息再清楚

不过

说 '&foo::abc'

boost::thread testThread(boost::bind(&foo::abc, f));
//                                   ^^^^^^^

另外,不需要boost::bind,这也应该有效

boost::thread testThread(&foo::abc, f);

请注意,这两者都会复制f,如果您想避免这种情况,则应使用以下任一方法

testThread(&foo::abc, &f);
testThread(&foo::abc, boost::ref(f));

现在,为什么main()class zoo的成员函数?

按照错误说的去做,将f.abc替换为foo::abc

boost::thread testThread(boost::bind(&foo::abc, f));

使用:

    boost::thread testThread(boost::bind(&foo::abc, f));

按照@Praetorian说的去做。一切正常:

//Title of this code
//Compiler Version 18.00.21005.1 for x86
#include <iostream>
#include <boost/asio.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
class zoo;
class foo
{
    private:
    public:
    foo(){}
    void abc()
    {
        std::cout << "abc" << std::endl;
    }
};
class zoo
{
    public:
    int main()
    {
        foo f;
        boost::thread testThread(boost::bind(&foo::abc, &f));
        testThread.join();
        return 0;
    }
}; 
int main()
{
    zoo{}.main();
}

直播: http://rextester.com/XDE37483