我刚刚开始使用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