2015-04-17 66 views
2

当我编译下面的一段代码时,出现以下错误。任何人都可以帮助我解决这个问题。谢谢。指向成员函数错误

错误:ISO C++禁止将绑定成员函数的地址形成指向成员函数的指针。说“& FOO :: ABC” [-fpermissive]

升压::螺纹testThread(升压::绑定(& 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; 
} 

回答

4

该错误消息可能不会真的是再清楚不过

Say ‘&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一个成员函数? ?

+0

即使在拆除类动物园后,我收到了同样的错误。 – shaikh

+0

@shaikh什么错误?所有这些选项[为我工作](http://coliru.stacked-crooked.com/a/93c8f533b7c466f5) – Praetorian

+0

住它的工作正常。我不知道为什么我得到一个长的错误信息。 thread.cpp :(。text + 0x74):对boost :: thread :: join()的未定义引用。 thread.cpp在函数中使用'__static_initialization_and_destruction_0(int,int)':'(')' thread.cpp :(。text + 0x95):未定义的引用'boost :: thread ::〜thread()' /tmp/ccAzOPoD.o: (.text + 0xf4):未定义的引用boost :: system :: generic_category()' thread.cpp :(。text + 0xfe):未定义的引用'boost :: system :: generic_category()' )' ... collect2:错误:ld返回1退出状态 – shaikh

1

做到像错误说,与foo::abc替换f.abc

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

用途:

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

编译器说:错误:预期的主要表达式之前'。'token – shaikh

+2

仍然不正确,应该是&foo :: abc –

0

做的@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

+0

为什么有两个主要功能? – shaikh

+2

@shaikh,这是你的代码,编译有点不同。 C++需要**全局**函数,名为'main' [见这里](http://en.cppreference.com/w/cpp/language/main_function)。在你的情况下,main()是'zoo'类的成员函数。如果没有全局的自由函数main(),C++将不知道如何启动程序,首先调用哪个函数 – grisha