【发布时间】:2013-07-26 15:13:12
【问题描述】:
我正在尝试使用线程调用我的一些成员函数。假设我有这个
class myclass
{
public:
myclass();
double function1();
void function2();
};
myclass::myclass()
{}
double myclass::function1()
{
...
return a double;
}
void myclass::function2()
{
//use a thread to call function 1
std::thread t(function1);//doesnt work!-wont compile
std::thread t2(myclass::function1);//doesnt work either -wont compile
std::thread t3(&myclass::function1);//doesnt work here either - wont compile
}
如何通过 C++ 中另一个成员函数内部的线程调用成员函数? 顺便说一下,我正在使用 Visual Studio 2013 Preview。
更新 2:
我按照我说的做了,现在有些代码部分编译得很好,有些则不能!
这是产生错误的新示例代码:
class xGramManipulator
{
public:
xGramManipulator();
void ReadMonoGram();
void ReadBiGram();
void ReadMonoGram(double &);
void ReadBiGram(double &);
void CreateMonoGramAsync();
void CreateBiGramAsync();
};
xGramManipulator::xGramManipulator()
{
}
void xGramManipulator::CreateMonoGramAsync()
{
thread t(&xGramManipulator::ReadMonoGram, this);
}
void xGramManipulator::CreateBiGramAsync()
{
thread t = thread(&xGramManipulator::ReadBiGram, this);
}
上面的代码(这两个 Async 成员函数)会产生以下错误:
错误信息:
错误 C2661: 'std::thread::thread' : 没有重载函数需要 2 个参数
【问题讨论】:
-
是什么阻止了您格式化您的问题?您已经成为活跃的 SO 成员将近两年了。此外,“不起作用!”很难描述您的技术问题。请做得更好。
-
@LightnessRacesinOrbit:原因很简单,我只是不小心按了 Enter 并提交了问题,然后我什至尝试格式化它。虽然提交后的秒数被“R. Martinho Fernandes”格式化.
-
好的,这是一个很好的理由。谢谢。
-
编辑后的代码示例对我来说编译得很好。不过,请确保您使用
#include <thread>并使用std::thread。另外,请不要覆盖您的原始问题并进行更改。你可以追加它,但现在你已经把所有的答案都搞砸了。 -
好的,包括在内!那么为什么它不能在 Visual Studio 2013 预览版中编译呢?你在哪里编译的?