[英]static const member initialization from file
How do you initialize a static const member with a value that is stored in a file? 如何使用存储在文件中的值初始化静态const成员? For example:
例如:
Class Foo
{
private:
static const String DataFromFile;
void InitData (void);
};
I know for a short value, I can initialize with: 我知道一个简短的值,我可以用:
const String DataFromFile = "Some Value";
But what if the value is really a "big" value and encrypted and stored in a disk file? 但是,如果该值确实是一个“大”值并加密并存储在磁盘文件中,该怎么办? I need to decrypt it before putting it into
DataFromFile
. 在将其放入
DataFromFile
之前,我需要对其解密。
Is there a way to do it or can I just forget it and treat it as a regular variable? 有没有办法做到这一点,或者我是否可以忘记并将其视为常规变量? That is, instead of:
也就是说,代替:
static const String DataFromFile;
can I just declare it as: 我可以声明为:
String DataFromFile;
and initialize it with a function? 并用一个函数初始化它?
How do you initialize a static const member with a value that is stored in a file?
如何使用存储在文件中的值初始化静态const成员? For example:
例如:
Like this: 像这样:
//X.h
#include <string>
class X
{
//...
static const std::string cFILE_TEXT_;
static const bool cINIT_ERROR_;
};
//X.cpp
//...#include etc...
#include <fstream>
#include <stdexcept>
namespace {
std::string getTextFromFile( const std::string& fileNamePath )
{
std::string fileContents;
std::ifstream myFile( fileNamePath.c_str() );
if( !(myFile >> fileContents) );
{
return std::string();
}
return fileContents;
}
}
const std::string X::cFILE_TEXT_( getTextFromFile( "MyPath/MyFile.txt" ) );
const bool X::cINIT_ERROR_( cFILE_TEXT_.empty() );
X::X()
{
if( cINIT_ERROR_ )
{
throw std::runtime_error( "xxx" );
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.