2015-04-17 64 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