我有一个C++类,该类在其构造函数中使用字符串(文件路径),将该文件加载到JSON中,然后使用一些JSON变量初始化另一个成员。
由于需要首先加载文件,并且需要初始化JSON(从流中初始化),因此我无法在成员初始化器列表中初始化thing
。我应该为JSON使用另一个包装器类,还是使用new ...?我该如何实现?
class Dummy
{
std::string _configFilePath;
json configJson;
Thing thing;
Dummy(std::string configFilePath = "../config.json") :
_configFilePath(configFilePath)
{
std::ifstream ifs(configFilePath);
ifs >> configJson;
thing(configJson["whatever"]); // thing can't be initialized here
}
};
请注意,
thing
不是默认可构造的。
最佳答案
您可以使用一个辅助函数来执行当前构造函数的操作:
class Dummy
{
std::string _configFilePath;
json configJson;
Thing thing;
Thing loader() {
std::ifstream ifs(_configFilePath);
ifs >> configJson;
return Thing(configJson["whatever"]);
}
Dummy(std::string configFilePath = "../config.json") :
_configFilePath(configFilePath), thing(loader())
{
}
};
这将构造
_configFilePath
和默认构造configJson
,然后调用loader
加载东西。 RVO应该直接在thing
中启用loader
的构造。
关于c++ - 如何在成员初始值设定项列表之外初始化类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60764035/