class MyClass
{
public:
friend void function(MyClass& mc)
{
std::cout << "Friend function from thread" << std::endl;
}
void init()
{
thr = std::thread(function, this);
thr.join();
}
private:
std::thread thr;
};
int main()
{
std::cout << "This is main function" << std::endl;
MyClass nc;
nc.init();
return 0;
}
Error C2065 'function': undeclared identifier
如何在不使用任何静态函数的类中创建线程?
最佳答案
我不知道为什么你的 friend 功能的查找在这种情况下不起作用,也许其他人知道。
但归档您想要的内容的最快方法是 lamdba 或声明您的函数。
例如。
class MyClass;
void function(MyClass& mc);
class MyClass
{
public:
friend void function(MyClass& mc)
...
void init()
{
// either do this
thr = std::thread([this](){function(*this);});
// or this note the std::ref. You are passing a reference. Otherwise there will be a copy
thr = std::thread(&function, std::ref(*this));
thr.join();
}
private:
std::thread thr;
};
....
关于c++ - 如何在类中创建线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802105/