我在类中创建四个线程时遇到问题,每个线程都使用另一个成员函数来打印每个 vector 的内容。但是,当我创建线程时,我在这 4 行上收到错误 no instance of constructor "std::thread::thread"matches the argument list
。我不知道为什么如果我尝试为线程使用另一个成员函数它不起作用。难道是因为他们在一个类(class)里?我该如何修复这 4 个错误?
class PrintfourVectors
{
private:
vector<string> one;
vector<string> two;
vector<string> three;
vector<string> four;
public:
void printOne()
{
// do stuff
}
void printTwo()
{
// do stuff
}
void printThree()
{
// do stuff
}
void printFour()
{
// do stuff
}
void makeFourThreads()
{
thread threadone(printOne); // error here
thread threadtwo(printTwo); // error here
thread threadthree(printThree); // error here
thread threadfour(printFour); // error here
threadone.join();
threadtwo.join();
threadthree.join();
threadfour.join();
}
};
最佳答案
一个问题是您正在调用非静态成员函数,并且这些函数有一个“隐藏”的第一个参数,该参数成为函数中的 this
指针。因此,当使用非静态成员函数创建线程时,您需要将对象实例作为参数传递给线程函数。
喜欢
thread threadone(&PrintfourVectors::printOne, this);
// ^^^^
// Pass pointer to object instance as argument to the thread function
关于c++ - 如何在C++类中创建四个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37371150/