我試圖創建一個嵌套的數據結構,是深許多層,其中每個「孩子」可以從他們的父母/祖父母/等訪問數據的數據...嵌套數據結構,讓孩子繼承父
爲例如拿這些數據結構:
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