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

时间:2014-11-18 18:57:29

标签: c++ qt function pointers

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

类定义标题

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

2 个答案:

答案 0 :(得分:0)

The documentation说:

  

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

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

答案 1 :(得分:0)

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

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