我正在尝试将类的函数与 std::thread 一起使用
以下代码片段返回错误
MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works
std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here
我需要创建一个带有指向该类的特定指针的线程:MyClass_ptr
那么,有没有办法使用这个特定的指针来使用该类的方法?
如果有用,这里是使用 Microsoft Visual Studio 2013 编译的完整代码
#include "stdafx.h"
#include <iostream>
#include <thread>
class MyClass
{
public:
void MyFunction();
void MyOtherFunction();
};
void MyClass::MyOtherFunction()
{
std::cout << "Inside MyOtherFunction" << std::endl;
std::cin.get();
}
void MyClass::MyFunction ()
{
std::cout << "Inside MyFunction" << std::endl;
std::cin.get();
}
int _tmain(int argc, _TCHAR* argv[])
{
MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works
std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here
delete MyClass_ptr;
MyClass_ptr = nullptr;
return 0;
}
您需要传递一个将在其上调用成员函数的对象(请记住,每个非静态成员函数都有一个隐式的this
范围) :
#include <thread>
class MyClass
{
public:
void MyFunction();
void MyOtherFunction();
};
int main()
{
MyClass *MyClass_ptr = new MyClass;
std::thread ThreadA(&MyClass::MyFunction, MyClass_ptr);
std::thread ThreadB(&MyClass::MyOtherFunction, MyClass_ptr );
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)