C++是否可以延迟常量静态成员的初始化?

des*_*tan 5 c++ qt static-initialization

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

Constants.h

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const FILE_NAME;
};

#endif // CONSTANTS_H
Run Code Online (Sandbox Code Playgroud)

Constants.cpp

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

const char* const Constants::FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();
Run Code Online (Sandbox Code Playgroud)

main.cpp中

#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();
}
Run Code Online (Sandbox Code Playgroud)

编译时,我得到:

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

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

是否有可能,如果没有,你还能建议克服这个问题?

谢谢

seh*_*ehe 11

典型解决方案

#ifndef CONSTANTS_H
#define CONSTANTS_H

class Constants
{
public:

    static const char* const getFILE_NAME();
};

#endif // CONSTANTS_H
Run Code Online (Sandbox Code Playgroud)

在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;
}
Run Code Online (Sandbox Code Playgroud)

  • 你不是存储指向临时字符串内容的指针吗?或者`toStdString()`是否返回对持久性东西的引用? (3认同)

Mik*_*our 7

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

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();
}
Run Code Online (Sandbox Code Playgroud)