简体   繁体   中英

Qt5: Strange compilation error while using QCommandLineParser class

For my application I had to derive QtCoreApplication and use QCommandLineParser. I declared QCommandLineOptions instances in a separate namespace and wanted to declare the parser in this namepsace as well. However I get an error that I don't quite understand.

namespace
{
    QCommandLineParser parser;
    
    const QCommandLineOption optA("optA", "defaultOptA");
    parser.addOption(optA); <-- error: unknown type name 'parser'
}

MyApp::MyApp(int argc, char *argv[])
    :QCoreApplication(argc, argv)
{
    setApplicationName("My App");
}

I have also tried declaring a QList<QCommandLineOption> so that I can add the options to it and add it the parser in on go using QCommandLineParser::addOptions , but that does not work either.

namespace
{
    QList<QCommandLineOption> options;
    
    const QCommandLineOption optA("optA", "defaultOptA");
    options << optA; <-- error: unknown type name 'options'
}

MyApp::MyApp(int argc, char *argv[])
    :QCoreApplication(argc, argv)
{
    setApplicationName("MyApp);

}

What am I doing wrong in both cases?

You can't have expressions like parser.addOption(optA) or options << optA in a namespace declaration. This is just C++ thing and has nothing to do with Qt. I would suggest you rather put the parser and optA variables in your MyApp class and initialize them in the MyApp constructor

class MyApp : public QCoreApplication
{
    ...

private:
    QCommandLineParser parser;
    const QCommandLineOption optA;
};

MyApp::MyApp(int argc, char *argv[])
    : QCoreApplication(argc, argv), optA("optA", "defaultOptA")
{
    parser.addOption(optA);
    
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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