gpt4 book ai didi

c++ - 非静态成员函数的无效使用(在 qt 中)

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:36:38 25 4
gpt4 key购买 nike

我在我的 mainwindow.h 类文件(标题?)中制作了我的函数原型(prototype):

    class MainWindow : public QMainWindow
{
Q_OBJECT

public:
void receiveP();

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

void MainWindow::receiveP()
{
dostuff
}

然后在我的 main.cpp 类文件的主要功能中,我尝试在线程中使用它:

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

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

最佳答案

您正在尝试将成员函数指针传递给 thread 类的构造函数,它需要一个普通(非成员)函数指针。

改为传入静态方法函数指针(或指向自由函数的指针),并显式为其提供对象的实例:

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

确保线程在您的窗口对象被破坏之前终止。

关于c++ - 非静态成员函数的无效使用(在 qt 中),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22749787/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com