簡體   English   中英

錯誤:在沒有對象的情況下無法調用成員函數'void Fortest :: run()'

[英]error: cannot call member function 'void Fortest::run()' without object|

我正在編寫一個非常簡單的c ++程序。

#include<iostream>
#include<thread>

class Fortest{
private:
    int x;
public:
    Fortest(int a)
    {
        x=a;
    }
    void run(void)
    {
        cout<<"test sucesses!"<<endl;
    }
};

int main()
{
    Fortest  hai(1);
    std::thread  t;

    t=std::thread(std::ref(hai),&Fortest::run());
    t.join();

    cout<<"program ends"<<endl;
    return 0;
}

而且,我不斷收到錯誤消息:“沒有對象就無法調用成員函數”。 誰能幫我解決這個問題?

您有兩個問題:

首先是調用線程函數,將指針傳遞給它返回的值。 您應該將指針傳遞給該函數

第二個問題是您以錯誤的順序傳遞了std::thread構造函數參數。 指向函數的指針是第一個參數,調用它的對象是第二個參數(這是函數的第一個參數)。

即應該是這樣的

t = std::thread(&Fortest::run, &hai);

你說錯了

嘗試:

Fortest  hai(1);
std::thread  t;

t=std::thread(&Fortest::run, std::ref(hai));
t.join();

或通過t=std::thread(&Fortest::run, &hai); 檢查std :: thread上的參數

現場演示

暫無
暫無

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

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