我剛剛開始使用C++ 11線程,我一直在努力(可能很愚蠢)的錯誤。 這是我的示例程序:C++ 11線程初始化與成員函數編譯錯誤
#include <iostream>
#include <thread>
#include <future>
using namespace std;
class A {
public:
A() {
cout << "A constructor\n";
}
void foo() {
cout << "I'm foo() and I greet you.\n";
}
static void foo2() {
cout << "I'm foo2() and I am static!\n";
}
void operator()() {
cout << "I'm the operator(). Hi there!\n";
}
};
void hello1() {
cout << "Hello from outside class A\n";
}
int main() {
A obj;
thread t1(hello1); // it works
thread t2(A::foo2); // it works
thread t3(obj.foo); // error
thread t4(obj); // it works
t1.join();
t2.join();
t3.join();
t4.join();
return 0;
}
是否有可能從一個純粹的成員函數啓動一個線程?如果不是,我怎麼能包裝我的foo函數從對象obj能夠創建這樣的線程? 在此先感謝!
這是編譯錯誤:
thread_test.cpp: In function ‘int main()’: thread_test.cpp:32:22: error: no matching function for call to ‘std::thread::thread()’
thread_test.cpp:32:22: note: candidates are:
/usr/include/c++/4.6/thread:133:7: note: std::thread::thread(_Callable&&, _Args&& ...) [with _Callable = void (A::*)(), _Args = {}]
/usr/include/c++/4.6/thread:133:7: note: no known conversion for argument 1 from ‘’ to ‘void (A::*&&)()’
/usr/include/c++/4.6/thread:128:5: note: std::thread::thread(std::thread&&)
/usr/include/c++/4.6/thread:128:5: note: no known conversion for argument 1 from ‘’ to ‘std::thread&&’
/usr/include/c++/4.6/thread:124:5: note: std::thread::thread()
/usr/include/c++/4.6/thread:124:5: note: candidate expects 0 arguments, 1 provided
嘗試一個簡單的lambda:'[&](){obj.foo();}'。 [Full code here](http://liveworkspace.org/code/4Fh1lL$1)。 – BoBTFish 2013-03-15 14:10:56
謝謝Angew,我一定會在將來的帖子中改變標籤。 – Rob013 2013-03-15 14:30:26