gpt4 book ai didi

c++ - 如何在成员初始值设定项列表之外初始化类成员

转载 作者:行者123 更新时间:2023-12-01 15:10:50 24 4
gpt4 key购买 nike

我有一个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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com