簡體   English   中英

如何在類內創建線程?

[英]How to create a thread inside a class?

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;
   }

錯誤C2065“功能”:未聲明的標識符

如何在不使用任何靜態函數的類內創建線程?

我不知道為什么您的朋友功能查找在這種情況下不起作用,也許有人知道。
但是,存檔所需內容的最快方法是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;

};
....

@mkaes擊敗了我,但我對您的function()進行了一些修改,使其接受指向該類的指針而不是引用。

  • 您不能像訪問其他成員函數那樣訪問類內的好友函數。

    1. 問題在於,即使您在類中將其聲明為朋友函數,您的朋友函數也沒有全局聲明。
    2. 因此,我們在類外部定義函數,並在內部保留一個Friend聲明。
    3. 現在,由於function()不知道類MyClass ,我們也必須向前聲明MyClass類。

碼:

#include <iostream>
#include <thread>

class MyClass;

void function(MyClass* mc)
{
    std::cout << "Friend function from thread" << std::endl;
}

class MyClass
{
public:
    void init()
    {
       thr = std::thread(function, this);
       thr.join();
        // function(this);
    }
    friend void function(MyClass* mc);
private:
    std::thread thr;

};

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

    return 0;
}

輸出:

這是主要功能
線程的朋友功能

編輯:

根據評論中的討論,我在此處發布的第一個代碼存在一個問題,即您無法調用成員函數或訪問friend function()內部的成員變量,因為該類是在以后定義的。 為了解決這個問題,下面是替代方法。 但是無論如何,@ mkaes從一開始就已經以這種方式回答了。

#include <iostream>
#include <thread>

class MyClass;
void function(MyClass* mc);

class MyClass
{
public:
    void init()
    {
       thr = std::thread(function, this);
       thr.join();
        // function(this);
    }
    friend void function(MyClass* mc)
    {
        std::cout << "Friend function from thread" << std::endl;
        mc->test();
    }
    int test(){}
private:
    std::thread thr;

};



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

    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM