Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
765 views
in Technique[技术] by (71.8m points)

c++ - invalid use of non-static member function( in qt)

I've prototyped my function in my mainwindow.h class file(header?):

    class MainWindow : public QMainWindow
{
    Q_OBJECT

    public:
    void receiveP();

Then in my main.cpp class file I tell the function what to do:

void MainWindow::receiveP()
{
     dostuff
}

Then in the main function of my main.cpp class file I try to use it in a thread:

 std::thread t1(MainWindow::receiveP);
 t1.detach();

Which gives me the error "invalid use of non-static member function 'void MainWindow::receiveP()'.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You're attempting to pass a member function pointer to the constructor of the thread class, which expects a normal (non-member) function pointer.

Pass in a static method function pointer (or pointer to a free function) instead, and explicitly give it the instance of your object:

// Header:
static void receivePWrapper(MainWindow* window);

// Implementation:
void MainWindow::receivePWrapper(MainWindow* window)
{
    window->receiveP();
}

// Usage:
MainWindow* window = this;   // Or whatever the target window object is
std::thread t1(&MainWindow::receivePWrapper, window);
t1.detach();

Make sure that the thread terminates before your window object is destructed.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...