简体   繁体   English

QT和C ++:无法在main()函数外调用函数

[英]QT and C++: can't call function outside main() function

I would like to know how to call the function Do_Download() from the SocketTest class outisde the main() function. 我想知道如何从SocketTest类调用函数Do_Download() ,而不是 main()函数。 The first cTest.Do_Download() does work, but when I call the test() function, the csTest.Do_Download() does not work. 第一个cTest.Do_Download()确实有效,但是当我调用test()函数时, csTest.Do_Download()不起作用。

So it looks like I can only acces SocketTest from inside the main() function, and not from any other function. 所以看起来我只能从main()函数内部访问SocketTest ,而不能从任何其他函数访问。

Does somebody know how this can be solved? 有人知道如何解决这个问题吗? Thanks! 谢谢!

main.cpp: main.cpp中:

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    SocketTest cTest;
        cTest.Do_Download();

    return a.exec();
}


void test()
{
    qDebug() << "test main functie";

    SocketTest csTest;
        csTest.Do_Download();
}

SocketTest.h: SocketTest.h:

#ifndef SOCKETTEST_H
#define SOCKETTEST_H

#include <QObject>
#include <QTcpSocket>
#include <QDebug>
#include <QHttp>
#include <QFile>
#include <QString>

class SocketTest : public QObject
{
    Q_OBJECT
public:
    explicit SocketTest(QObject *parent = 0);


   void Do_Download();
signals:

public slots:

    void stateChanged ( int state );
    void responseHeaderReceived ( const QHttpResponseHeader & resp );
    void requestFinished ( int id, bool error );

private:
    QTcpSocket *socket;
    QHttp *http;
    QHttp *http2;

};

#endif // SOCKETTEST_H

If your DoDownload function is doing anything asynchronously (likely, when dealing with the Qt networking classes), the SocketTest you are creating in test() is being destroyed before it can act on any return value. 如果您的DoDownload函数异步执行任何操作(可能在处理Qt网络类时),您在test()中创建的SocketTest在它可以对任何返回值执行操作之前就会被销毁。

It works in main() because the event loop starts and the SocketTest instance hangs around. 它在main()工作,因为事件循环启动并且SocketTest实例挂起。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM