如何通过在线程中调用方法来更改av1的属性? C ++在此代码中,编译器是正常的,但在运行时会生成致命错误。

#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/

10-10 05:35