gpt4 book ai didi

c++ - 通过函数调用 C++ 中的线程更改对象属性

转载 作者:行者123 更新时间:2023-11-28 04:17:27 25 4
gpt4 key购买 nike

如何更改 av1 的属性以防止在线程中调用方法? C++ 在这段代码中,编译正常,但在运行时产生了 fatal error 。

#include <iostream>
#include<thread>

using namespace std;

class Airplane{

public:
int vel = 0;

Airplane *air1;

void change_av1(){
air1->vel = 3;
cout << air1->vel << endl;
system("pause");
}
};

void myFunction();

int main(){

Airplane *air1=new Airplane();

myFunction();

return 0;
}

void myFunction(){

Airplane *object=new Airplane();

thread first(&Airplane::change_av1, object); // meu método dentro da thread

first.join();
}

最佳答案

你的代码全错了。它应该看起来更像这样:

#include <iostream>
#include <thread>
using namespace std;

class Airplane{
public:
int vel = 0;

void change_vel(){
vel = 3;
cout << vel << endl;
}
};

void myFunction();

int main(){
myFunction();
system("pause");
return 0;
}

void myFunction(){
Airplane *object = new Airplane;
thread first(&Airplane::change_vel, object);
first.join();
delete object;
}

关于c++ - 通过函数调用 C++ 中的线程更改对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56301350/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com