C ++ std :: thread和方法类 [英] C++ std::thread and method class

查看:86
本文介绍了C ++ std :: thread和方法类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用带有std :: thread的类的函数

i'm trying to use a function of a class with std::thread

以下代码段返回错误

MyClass *MyClass_ptr = new MyClass;
MyClass_ptr->MyFunction(); // Works

std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here

我需要创建一个带有该类特定指针的线程:MyClass_ptr

I need to make a thread with that specific pointer to the class: MyClass_ptr

那么,有没有办法使用此特定指针使用该类的方法?

So, is there a way to use a method of that class using this specific pointer ?

如果在这里有用是使用Microsoft Visual Studio 2013编译的完整代码

If it's useful here is the full code compiled with Microsoft Visual Studio 2013

#include "stdafx.h"

#include <iostream>
#include <thread>

class MyClass 
{

public:
    void MyFunction();
    void MyOtherFunction();

};

void MyClass::MyOtherFunction()
{
    std::cout << "Inside MyOtherFunction" << std::endl;
    std::cin.get();
}

void MyClass::MyFunction ()
{
    std::cout << "Inside MyFunction" << std::endl;
    std::cin.get();
}

int _tmain(int argc, _TCHAR* argv[])
{
    MyClass *MyClass_ptr = new MyClass;

    MyClass_ptr->MyFunction(); // Works
    std::thread ThreadA(MyClass_ptr->MyFunction() ); // Error here
    std::thread ThreadB(MyClass_ptr->MyOtherFunction() ); // Error here


    delete MyClass_ptr;
    MyClass_ptr = nullptr;

    return 0;
}


推荐答案

您需要传递一个对象在其上将调用成员函数(请记住,每个非静态成员函数都有一个隐式 this 参数):

You need to pass an object on which the member function will be called (remember, every non-static member function has an implicit this parameter) :

#include <thread>

class MyClass
{
    public:
    void MyFunction();
    void MyOtherFunction();
};

int main()
{
    MyClass *MyClass_ptr = new MyClass;

    std::thread ThreadA(&MyClass::MyFunction, MyClass_ptr);
    std::thread ThreadB(&MyClass::MyOtherFunction, MyClass_ptr );
}

这篇关于C ++ std :: thread和方法类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆