子级从父级继承数据的嵌套数据结构

Nested data structure where children inherit data from parent

本文关键字:嵌套 数据结构 数据 继承      更新时间:2023-10-16

我正在尝试创建一个嵌套的数据结构,它有很多层深,每个"子"都可以从他们的父/孙等访问数据。。。

以以下数据结构为例:

struct GrandChild {
    int someGrandChildData;
};
struct Child {
    int someChildData;
    std::vector<GrandChild> vgrandChild;
};
struct Parent {
    int someParentData;
    std::vector<Child> vchild;
};
struct GrandParent {
    int someGrandParentData;
    std::vector<Parent> vparent;
};

我想访问数据的方式是这样的:

void main()
{
    // create and fill in the data
    GrandParent gp;
    for (int pNum = 0; pNum < 3; pNum++)
    {
        gp.vparent.push_back(Parent());
        for (int cNum = 0; cNum < 3; cNum++)
        {
            gp.vparent[pNum].vchild.push_back(Child());
            for (int gcNum = 0; gcNum < 3; gcNum++)
            {
                gp.vparent[pNum].vchild[cNum].vgrandChild.push_back(GrandChild());
                // call function and ONLY pass a GrandChild
                func(gp.vparent[pNum].vchild[cNum].vgrandChild[gcNum]);
            }
        }
    }
}
void func(GrandChild &gc)
{
    int result = gc.someGrandChildData;
    // no need to pass GrandParent, Parent, or Child because
    // GrandChild can access all of the data from them
    result += gc.someChildData; // <<-- how can I achieve something like this
    result += gc.someParentData; // <<-- how can I achieve something like this
    result += gc.someGrandParentData; // <<-- how can I achieve something like this
}

我之所以尝试这样做,是因为我在每个嵌套层都有许多数据成员的结构,当我调用函数时,必须在每个函数调用中传递大量参数,这非常令人讨厌,而且为了保持组织混乱。

如有任何帮助,我们将不胜感激。

您可以通过跟踪每个人的Parent来实现这一点(我们称之为Node)。因此,对于每个节点,在其内部创建其直接父对象的对象,并对每个层(GrandChild、Child、Parent..等)执行此操作。

所以每个GrandChild将有一个Child对象,每个Child将有一个子Parent对象,并且每个Parent将有一子GrandParent对象。

然后你就可以做这样的事情:

void func(GrandChild &gc)
{
    int DataFromTheGranChild  = gc.DataFromGrandChild;
    int DataFromTheChild      = gc.Child.DataFromChild;
    int DataFromTheParent     = gc.Child.Parent.DataFromParent;
    int DataFromTheGradParent = gc.Child.Parent.GrandParent.DataFromGrandParent;
    //..
}

您可以尝试只使用一种类型的结构。

struct Entity{
    int Data;
    Entity* Child;
    Entity* Parent;
};