C ++是否可以延迟恒定静态成员的初始化? [英] C++ is it possible to delay initialization of constant static member?
问题描述
我正在使用Qt,但这是一个通用的C ++问题.我的情况很简单,我有一个Constants
类,它具有一个恒定的静态成员,我希望在进行某些函数调用后对其进行初始化.
I am using Qt but this is a generic C++ question. My case is simple, I have a class Constants
which has a constant static member which I want it to be initialized after certain function calls are made.
Constants.h
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
static const char* const FILE_NAME;
};
#endif // CONSTANTS_H
Constants.cpp
Constants.cpp
#include "constants.h"
#include <QApplication>
const char* const Constants::FILE_NAME = QApplication::applicationFilePath().toStdString().c_str();
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();
}
编译时我得到了:
QCoreApplication :: applicationFilePath:请首先实例化QApplication对象
QCoreApplication::applicationFilePath: Please instantiate the QApplication object first
所以这里的问题很明显.在Constants.cpp中调用QApplication的静态函数时,Qt尚未安装QApplication.我需要以某种方式等待,直到在main.cpp中通过QApplication a(argc, argv);
行
So problem here is obvious. When QApplication's static function is called in Constants.cpp QApplication is not installed by Qt yet. I need to somehow wait until QApplication a(argc, argv);
line is passed in main.cpp
是否有可能,如果不能,您还有什么建议可以克服呢?
is it possible and if not what else could you suggest to overcome this?
谢谢
推荐答案
一种选择是从函数返回它,并将其保留在静态变量中.该函数将在首次调用该函数时初始化.
One option is to return it from a function, keeping it in a static variable. This will be initialised when the function is first called.
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();
}
这篇关于C ++是否可以延迟恒定静态成员的初始化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!