gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:53:38 24 4
gpt4 key购买 nike

我正在使用 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();

主要.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();
}

编译时我得到:

QCoreApplication::applicationFilePath: Please instantiate the QApplication object first

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

是否有可能,如果不可能,您还有什么建议可以克服这个问题?

谢谢

最佳答案

典型解决方案:

#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;
}

关于C++ 是否可以延迟常量静态成员的初始化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7806589/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com