c++ 在创建时将构造函数参数从 parent object 传递到 child object

c++ pass constructor parameter from parent object to child object on creation

这个问题太具体了,我很难找到答案...

有没有办法将 parent class' 构造函数参数自动传递给内部 child class/struct 的构造函数?

我想从数据文件中读取行来填充我的 class 及其在创建时的 children,所以我也想将数据文件传递到 child

我的数据结构是这样的:

vector of class Par(ifstream parameter)
   membervar
   membervar
   vector of struct Chld(the same ifstream parameter)
       membervar
       vector membervar

并且我希望能够构建并填充所有 children 和成员,只需调用 parent 的创建并为其提供数据文件以从 [=16 读取信息=]

vector<Par> parents(num, Par(datafile));

这将是我理想的创作路线,既快速又简单,我可以在之后立即关闭数据文件,因为我拥有我需要的所有信息

这可能吗?默认构造函数不会只在 child 中调用吗?我希望以后不用再回去填空的成员,但如果我必须这样做,我想这也无济于事

直接通过?

class Par {
    std::vector<Chld> children;

public:
    Par(std::ifstream& file)
    { 
        children.push_back(Chld(file));  // pre-C++11
        children.emplace_back(file);     // post-C++11
    }
};