我有两个类(class)。
class first
{
public:
int sum (int a, int b)
{
return a+b;
}
};
class second
{
private:
std::thread t1, t2;
int sum (int a, int b, int c)
{
return a+b+c;
}
public:
void execute()
{
t1 = std::thread (&second::sum, this, 10,20,30); //calling same class function
t2 = std::thread (&first::sum, /*what will be here*/, 10,20); // trying to call another class function
}
};
int main()
{
second s;
s.execute();
return 0;
}
我需要传递什么来代替/* 这里会是什么 */
最佳答案
您需要一个 first
的实例(或指向至少与线程一样长的 first
实例的指针):
传递实例:
first f;
t2 = std::thread (&first::sum, f, 10,20);
传递一个指针:
// assume m_f is a data member of type first
t2 = std::thread (&first::sum, &m_f, 10,20);
选择哪一个取决于所需的语义。在这种情况下,first::sum
成为成员非静态成员函数(或根本不是成员函数)毫无意义。
如果您选择使 first::sum
成为 static
成员,那么您将不需要 first
的实例:
t2 = std::thread (&first::sum, 10, 20);
关于c++ - 如何在线程c++11中调用二类成员函数中的一类成员函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23201706/