c++如何在类中如何创建另一个类的成员函数的线程
时间: 2024-04-30 22:19:40 浏览: 6
在C++中,要在一个类中创建另一个类的成员函数的线程,可以使用C++11中的std::thread库。
首先,在类中定义一个函数来启动线程,例如:
```
void MyClass::startThread() {
// 创建线程并绑定成员函数
std::thread t(&MyOtherClass::myFunction, &otherClassInstance);
// 等待线程完成
t.join();
}
```
在这个例子中,我们假设我们要创建一个线程来执行另一个类MyOtherClass的myFunction()函数。我们将线程绑定到myFunction()函数,并传递MyOtherClass的实例作为参数。
然后,我们可以在startThread()函数中创建线程,并通过调用join()函数等待线程完成。
需要注意的是,我们需要使用&符号来获取MyOtherClass实例的地址,并使用std::thread的构造函数来绑定成员函数。
完整的示例代码如下:
```
#include <iostream>
#include <thread>
class MyOtherClass {
public:
void myFunction() {
std::cout << "MyOtherClass::myFunction() called" << std::endl;
}
};
class MyClass {
public:
void startThread() {
std::thread t(&MyOtherClass::myFunction, &otherClassInstance);
t.join();
}
private:
MyOtherClass otherClassInstance;
};
int main() {
MyClass myClass;
myClass.startThread();
return 0;
}
```