为什么不编译带有函数指针的代码?

Why doesn't this code with a function pointers compile?

本文关键字:代码 指针 函数 编译 为什么不      更新时间:2023-10-16

我想传递一个函数指针作为参数。

类定义标头

class Networking : public QObject
{
    Q_OBJECT
public:
    explicit Networking(QObject *parent = 0);
    QNetworkAccessManager* manager;
private:
    QUrl buildCall(QString method, QMap<QString, QString> parameters);
public slots:
    void reply(QNetworkReply* reply, void(*ptr)(const void *)); // error here
};

在类源中

Networking::Networking(QObject *parent) : QObject(parent)
{
    this->manager = new QNetworkAccessManager(this);
}
void Networking::reply(QNetworkReply* reply, void(*ptr)(const void *)) // error here
{
    //some code
}

编译收到错误:在"void"处解析错误

命令:

/usr/lib/qt/bin/moc -DQT_WEBKITWIDGETS_LIB -DQT_WEBKIT_LIB -DQT_WIDGETS_LIB -DQT_NETWORK_LIB -DQT_GUI_LIB -DQT_CORE_LIB -I/usr/lib/qt/mkspecs/linux-g++ -I/home/dev/cpp/net-client -I/usr/include/qt -I/usr/include/qt/QtWebKitWidgets -I/usr/include/qt/QtWebKit -I/usr/include/qt/QtWidgets -I/usr/include/qt/QtNetwork -I/usr/include/qt/QtGui -I/usr/include/qt/QtCore -I. -I/usr/include/c++/4.9.1 -I/usr/include/c++/4.9.1/x86_64-unknown-linux-gnu -I/usr/include/c++/4.9.1/backward -I/usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.1/include -I/usr/local/include -I/usr/lib/gcc/x86_64-unknown-linux-gnu/4.9.1/include-fixed -I/usr/include ../project/Networking.h -o moc_apihandler.cpp

我尝试使用,但收到相同的错误

typedef void (*ptr)(const void*);

文档说:

函数指针不能是信号或插槽参数

建议的解决方法是使用 typedef 或函数对象 - 您自己的层次结构,或者如果可以,std::function/boost::function

您发出的命令不是C++编译,而是 Qt 元对象编译器 (moc)。 moc是一个预处理器,它将Qt C++扩展转换为普通C++以进行适当的编译。

错误消息指示void不是预期的,并且假设它引用函数返回类型并且与函数指针无关,则错误很可能在前面的紧随行或语句中(不包括空格和注释) - 需要更多上下文才能确切地查看内容。 如果前面的行是包含文件,则需要查看包含文件的末尾。 常见错误包括缺少分号和包含文件末尾缺少换行符。