5

我正在使用 Qt,但这是一个通用的 C++ 问题。我的情况很简单,我有一个类Constants,它有一个常量静态成员,我希望在进行某些函数调用后对其进行初始化。

常量.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const FILE_NAME;
};

#endif // CONSTANTS_H

常量.cpp

#include "constants.h"
#include <QApplication>

const char* const Constants::FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();

主文件

#include <QtGui/QApplication>
#include "mainwindow.h"
#include "constants.h"
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    qDebug()<< "name: "<<Constants::FILE_NAME;
    //for those who are unfamiliar with Qt, qDebug just prints out
    return a.exec();
}

编译时我得到:

QCoreApplication::applicationFilePath: 请先实例化QApplication对象

所以这里的问题很明显。在 Constants.cpp 中调用 QApplication 的静态函数时,Qt 尚未安装 QApplication。我需要以某种方式等到QApplication a(argc, argv);在 main.cpp 中传递行

有可能吗?如果没有,你还能建议什么来克服这个问题?

谢谢

4

2 回答 2

11

典型解决方案:

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const getFILE_NAME();
};

#endif // CONSTANTS_H

而在cpp

#include "constants.h"
#include <QApplication>

const char* const Constants::getFILE_NAME()
{
    static const char* const s_FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();

    return s_FILE_NAME;
}
于 2011-10-18T11:41:58.340 回答
8

一种选择是从函数中返回它,将其保存在静态变量中。这将在第一次调用该函数时被初始化。

char const * const file_name()
{
    // Store the string, NOT the pointer to a temporary string's contents
    static std::string const file_name =
        QApplication::applicationFilePath().toStdString();
    return file_name.c_str();
}
于 2011-10-18T11:45:47.937 回答