[英]How to initialize class member outside the member initializer list
I have a C++ class that takes a string (file path) in its constructor, loads that file into a JSON and then uses some of the JSON variables to initialize another member.我有一个 C++ 类,它在其构造函数中接受一个字符串(文件路径),将该文件加载到 JSON 中,然后使用一些 JSON 变量来初始化另一个成员。
As the file needs to be loaded first, and the the JSON initialized (from stream), I cannot initialize thing
in the member initializer list.由于文件需要先加载,并且 JSON 初始化(来自流),我无法初始化成员初始化列表中的thing
。 Should I use another wrapper class for the JSON, use new...?我应该为 JSON 使用另一个包装类,使用新的...? How can I achieve this?我怎样才能做到这一点?
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
}
};
Note that thing
is not default constructible.请注意, thing
不是默认可构造的。
Is Thing
both default constructable and move-assignable? Thing
是否既可默认构造又可移动分配? If so:如果是这样的话:
class Dummy
{
std::string _configFilePath;
json configJson;
Thing thing;
Dummy(std::string configFilePath = "../config.json") :
_configFilePath(configFilePath)
{
std::ifstream ifs(configFilePath);
ifs >> configJson;
thing = Thing(configJson["whatever"]); // move-assign a new object
}
};
You can use a helper function to do what the current constructor does:您可以使用辅助函数来执行当前构造函数的操作:
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())
{
}
};
This will construct _configFilePath
and default construct configJson
, then call loader
to load the thing.这将构造_configFilePath
和默认构造configJson
,然后调用loader
来加载事物。 RVO should enable construction of thing
directly in loader
. RVO 应该能够直接在loader
构建thing
。
You can use the combination of a delegating constructor and a helper function that loads the json
object to properly initilize the objects.您可以结合使用委托构造函数和加载json
对象的辅助函数来正确初始化对象。
class Dummy
{
std::string _configFilePath;
json _configJson;
Thing _thing;
// Use a delegating constructor
Dummy(std::string configFilePath = "../config.json") :
Dummy(configFilePath, getConfig(configFilePath) {}
Dummy(std::string configFilePath, json configJson) :
_configFilePath(configFilePath),
_configJson(configJson),
_thing(configJson["whatever"]) {}
// Load and return the json object.
static json getConfig(std::string configFilePath)
{
std::ifstream ifs(configFilePath);
json configJson;
ifs >> configJson;
return configJson;
}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.