我想在C++11中使用多线程在自己的线程中调用类成员函数。我已经能够让它与全局函数一起工作:
#include <thread>
#include <iostream>
void Alpha(int x)
{
while (true)
{
std::cout << x << std::endl;
}
}
int main()
{
std::thread alpha_thread(Alpha, 5);
alpha_thread.join();
return 0;
}但是,我无法使用类成员函数对其进行编译:
#include <thread>
#include <iostream>
class Beta
{
public:
void Gamma(int y)
{
while (true)
{
std::cout << y << std::endl;
}
}
};
int main()
{
Beta my_beta;
std::thread gamma_thread(my_beta.Gamma, 5);
gamma_thread.join();
return 0;
}编译错误为:
no matching function for call to 'std::thread::thread(<unresolved overloaded function type>)'
std::thread gamma_thread(my_beta.Gamma, 5);
^我做错了什么?
发布于 2015-04-21 01:29:59
您需要传递两个东西:指向成员的指针和对象。在没有对象的情况下,不能在C++中调用非静态成员函数(如Gamma)。正确的语法应该是:
std::thread gamma_thread(&Beta::Gamma, // the pointer-to-member
my_beta, // the object, could also be a pointer
5); // the argument您可以将这里的my_beta视为Gamma()的第一个参数,而将5视为第二个参数。
发布于 2015-04-21 01:30:02
您需要命名函数,然后将调用该函数的对象作为显式隐式this参数传递。:)
std::thread gamma_thread(&Beta::Gamma, my_beta, 5);诚然,这有点抽象泄漏。
发布于 2015-04-21 01:30:49
您的程序中存在多个问题
this是成员函数的隐式参数,您需要传递函数&Beta::Gamma.
修改后的源
#include <thread>
#include <iostream>
class Beta
{
public:
void Gamma(int y)
{
while (true)
{
std::cout << y << std::endl;
}
}
};
int main()
{
Beta my_beta;
std::thread gamma_thread(&Beta::Gamma, my_beta, 5);
gamma_thread.join();
return 0;
}https://stackoverflow.com/questions/29754438
复制相似问题