2012-08-27 58 views
9

我試圖創建一個控制檯應用程序與Qt並試圖檢索參數時面臨真正奇怪的行爲。我的課程源自QCoreApplication,它具有通常應將所有參數放入strings列表中的功能。但在某些情況下,這種通話以分段故障結束。用戶的參數是空的QCoreApplication在神祕案件

下面的代碼:

的main.cpp

#include "Diagramm.h" 

int main(int argc, char *argv[]) 
{ 
    Diagramm application(argc, argv); 
    application.run(); 
    return EXIT_SUCCESS; 
} 

Diagramm.h

#include <QCoreApplication> 
#include <iostream> 
#include <QStringList> 
#include <QFile> 
#include <QDebug> 


class Diagramm : public QCoreApplication 
{ 
    Q_OBJECT 

    public: 
     Diagramm(int argc, char *argv[]); 
     void run(); 
    private: 
     void testArguments(); 
    signals: 
    public slots: 
}; 

Diagramm.cpp

#include "Diagramm.h" 

Diagramm::Diagramm(int argc, char *argv[]) : QCoreApplication(argc, argv) 
{ 
    //std::cout << "calling Diagramm constructor" << std::endl; 
} 

void Diagramm::run() 
{ 
    testArguments(); 
} 

void Diagramm::testArguments() 
{ 
    //get source and target files from arguments 
    QStringList arguments = this->arguments(); 

    if(arguments.count() < 2) 
    { 
     std::cout << "Missing arguments" << std::endl; 
     return exit(1); 
    } 
} 

當編譯和執行上面的代碼,一切正常很好,但是當我取消在Diagramm的構造行我有

我一直在對於小時,閱讀Qt的文檔上的功能testArguments第一線分段錯誤(調用arguments())論壇...有人知道可以從哪裏來?任何想法將不勝感激。

注意:我沒有故意撥打exec函數,因爲我不需要任何事件循環。

回答

14

Q(核心)應用希望argcargv參照,所以你的構造應該閱讀

Diagramm(int& argc, char **argv[]) 

如果你不這樣做,它可能在某些情況下工作,並導致段錯誤或其他人的奇怪行爲,如你遇到的。似乎是一個常見的錯誤,在閱讀文檔時不容易發現。

+2

就是這樣。非常感謝 !對於其他人,上面的代碼應該是:(在main.cpp中)'Diagramm application(argc,&argv);'(in Diagramm.cpp)'Diagramm :: Diagramm(int&argc,char ** argv []):QApplication(argc, * argv的)' – Ote

0

arguments()是靜態函數太行應該是:

QStringList arguments = QCoreApplication::arguments(); 
+1

確實很清楚,但除此之外不應有任何區別。 –