c++ - 如何在类中创建线程?

标签 c++

class MyClass
{
    public:
        friend void function(MyClass& mc)
        {
            std::cout << "Friend function from thread" << std::endl;
        }    
        void init()
        {
            thr = std::thread(function, this);
            thr.join();
        }

    private:
        std::thread thr;

};

  int main()
   {
    std::cout << "This is main function" << std::endl;
    MyClass nc;
    nc.init();

    return 0;
   }

Error C2065 'function': undeclared identifier

如何在不使用任何静态函数的类中创建线程?

最佳答案

我不知道为什么你的 friend 功能的查找在这种情况下不起作用,也许其他人知道。
但归档您想要的内容的最快方法是 lamdba 或声明您的函数。
例如。

class MyClass;
void function(MyClass& mc);
class MyClass
{
public:
    friend void function(MyClass& mc)
    ...
    void init()
    {
        // either do this
        thr = std::thread([this](){function(*this);});
        // or this note the std::ref. You are passing a reference. Otherwise there will be a copy
        thr = std::thread(&function, std::ref(*this));
        thr.join();
    }

private:
    std::thread thr;

};
....

关于c++ - 如何在类中创建线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54802105/

相关文章:

c++ - 移位 `char` 与 `unsigned char`

c++ - (Visual Studio) 尝试将 Microsoft 库与 SFML 库静态链接时出现大量链接器错误

c++ - 为什么在这个宏中一个地方需要双磅而其他地方不需要?

c++ - 评论中的字符是什么意思?

c++ - 从 STL 容器继承并删除 `new` 运算符以防止由于缺少虚拟析构函数而导致未定义的行为是否有意义?

c++ - 二维 vector 的打印内容

c++ - 获取QtDesigner制作的Widget指针

c++ - 'A' 的整数值

c++ - 使用 opencv 在 C++ 中将 3d 点从相机空间转换为对象空间

c++ push_back 无法正常工作