静态const成员从文件初始化

Huy*_*ham 2 c++ static initialization const

如何使用存储在文件中的值初始化静态const成员?例如:

Class Foo
{
private:
  static const String DataFromFile;
  void InitData (void);
};
Run Code Online (Sandbox Code Playgroud)

我知道一个简短的值,我可以初始化:

const String DataFromFile = "Some Value";
Run Code Online (Sandbox Code Playgroud)

但是,如果该值实际上是一个"大"值并加密并存储在磁盘文件中该怎么办?在放入之前我需要解密它DataFromFile.

有没有办法做到这一点,还是我可以忘记它并将其视为常规变量?也就是说,而不是:

static const String DataFromFile;
Run Code Online (Sandbox Code Playgroud)

我可以将其声明为:

String DataFromFile;
Run Code Online (Sandbox Code Playgroud)

并用函数初始化它?

Wer*_*mus 5

如何使用存储在文件中的值初始化静态const成员?例如:

像这样:

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