简体   繁体   中英

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

I am writing a really simple c++ program.

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

And I am constantly getting the error "cannot call a member function without an object". Could anyone help me to solve this problem?

You have two problems:

The first is that you call the thread function, passing a pointer to the value it returns. You should pass a pointer to the function .

The second problem is that you pass the std::thread constructor arguments in the wrong order. The pointer to the function is the first argument, and the object to call it on is the second (which is the first argument to the function).

Ie it should be something like

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

You are calling it the wrong way

Try:

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

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

or do so by t=std::thread(&Fortest::run, &hai); Check the arguments on std::thread

Live demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM