c++是否可以延迟常量static成员的初始化?
C++ is it possible to delay initialization of constant static member?
我正在使用Qt,但这是一个通用的c++问题。我的情况很简单,我有一个类Constants
,它有一个常量静态成员,我希望它在某些函数调用后初始化。
Constants.h
#ifndef CONSTANTS_H
#define CONSTANTS_H
class Constants
{
public:
static const char* const FILE_NAME;
};
#endif // CONSTANTS_H
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对象
所以这里的问题很明显。当在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
#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;
}
一种选择是从函数返回,将其保存在静态变量中。这将在函数第一次被调用时初始化。
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++成员初始化
- c++构造函数成员初始化:传递参数
- C++正确的指针成员初始化
- 将另一个类的对象传递到当前类C++的构造函数中(不是成员初始化)
- WinLamb 错误:成员初始化非法
- 使用其他成员初始化结构的成员?
- C++模板类静态成员初始化
- 解释了构造函数成员初始化列表
- 如何在成员初始化列表中声明共享指针
- C++入门5版:使用get成员初始化另一个与shared_ptr无关的对象
- C++11 默认类成员初始化与初始值设定项列表同时
- 调用非默认构造函数作为成员初始化
- C++模板成员初始化:用右值移动构造,但用左值移动引用
- 类成员初始化C++
- 在成员初始化列表中,我可以创建对列表中不在列表中的成员变量的引用
- C :(不重复)积分静态成员初始化(不仅是声明!),导致链接器错误,原因
- 如何调用成员初始化器列表中参考成员的构造函数
- C 构造函数采用成员初始化器
- 与其他静态const成员初始化静态常量成员
- 静态内联成员初始化顺序