无效使用非静态成员函数(在qt中) [英] invalid use of non-static member function( in qt)

查看:3712
本文介绍了无效使用非静态成员函数(在qt中)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的mainwindow.h类文件(header?)中创建了我的函数:

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

    class MainWindow : public QMainWindow
{
    Q_OBJECT

    public:
    void receiveP();

然后在我的main.cpp类文件中我告诉函数该做什么:

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

void MainWindow::receiveP()
{
     dostuff
}

然后在main.cpp类文件的main函数中,我尝试在一个线程中使用它:

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();

这给出了错误无效使用非静态成员函数void MainWindow :: receiveP )'。

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

推荐答案

您尝试传递一个成员函数指针到线程的构造函数

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.

这篇关于无效使用非静态成员函数(在qt中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆