我试图创建一个嵌套的数据结构,是深许多层,其中每个“孩子”可以从他们的父母/祖父母/等访问数据的数据...嵌套数据结构,让孩子继承父
为例如拿这些数据结构:
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
}
我想这样做,因为我有马的结构每个嵌套层都有数据成员,当我调用函数时,必须将大量参数传递给每个函数调用并且变得乱七八糟以保持组织性,这是非常令人讨厌的。
任何帮助将不胜感激。
你有没有关于使用多态和虚函数? – NathanOliver
我曾经想过,但只是不知道该怎么做。我以前使用过一些多态和虚函数,但我并不十分精通。 – Stanton