类成员函数做回调的有关问题
类成员函数做回调的问题
widget.h:
class Widget : public QWidget
{
Q_OBJECT
typedef void(*AAA)(char type, char *value);
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void getBTNameButtonClicked();
void reg(AAA a);
private:
Ui::Widget *ui;
AAA aaa;
};
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->getBTNameButton, SIGNAL(clicked()), this, SLOT(getBTNameButtonClicked()));
reg((AAA)&Widget::eventReady);
}
Widget::~Widget()
{
delete ui;
}
void Widget::getBTNameButtonClicked()
{
char type = 0x01;
char value[2] = {0x69, 0x6a};
this->aaa(type, value);
}
void Widget::reg(AAA a)
{
aaa = a;
}
void Widget::eventReady(char type, char *value)
{
qDebug() << "eventReady....................................";
qDebug("<Event> type = 0x%x\n", (unsigned char)type);
}
代码如上,我将一个类的成员函数作为回调函数时,成员函数可以被调用,但是函数参数却不能被正确传递,参数是一个随机数。如果将该成员函数加上限定符static,则是可以被正确传递的,求解。。。
------解决思路----------------------
回调函数只能是全局函数,如果要写在类内部,只能是static函数
------解决思路----------------------
我基本上看了一下,同2楼说的一样,在构造函数中你把eventReady作为回调函数,把函数指针付给了aaa
这个肯定会报错,成员函数要作为回调的函数指针必须是static的,这涉及到函数指针生存期以及vtable是否能获取到正确的
函数地址。
widget.h:
class Widget : public QWidget
{
Q_OBJECT
typedef void(*AAA)(char type, char *value);
public:
explicit Widget(QWidget *parent = 0);
~Widget();
public slots:
void getBTNameButtonClicked();
void reg(AAA a);
private:
Ui::Widget *ui;
AAA aaa;
};
widget.cpp:
#include "widget.h"
#include "ui_widget.h"
#include <QDebug>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
connect(ui->getBTNameButton, SIGNAL(clicked()), this, SLOT(getBTNameButtonClicked()));
reg((AAA)&Widget::eventReady);
}
Widget::~Widget()
{
delete ui;
}
void Widget::getBTNameButtonClicked()
{
char type = 0x01;
char value[2] = {0x69, 0x6a};
this->aaa(type, value);
}
void Widget::reg(AAA a)
{
aaa = a;
}
void Widget::eventReady(char type, char *value)
{
qDebug() << "eventReady....................................";
qDebug("<Event> type = 0x%x\n", (unsigned char)type);
}
代码如上,我将一个类的成员函数作为回调函数时,成员函数可以被调用,但是函数参数却不能被正确传递,参数是一个随机数。如果将该成员函数加上限定符static,则是可以被正确传递的,求解。。。
------解决思路----------------------
回调函数只能是全局函数,如果要写在类内部,只能是static函数
------解决思路----------------------
我基本上看了一下,同2楼说的一样,在构造函数中你把eventReady作为回调函数,把函数指针付给了aaa
这个肯定会报错,成员函数要作为回调的函数指针必须是static的,这涉及到函数指针生存期以及vtable是否能获取到正确的
函数地址。