我對C++很陌生,在尋找關於下列問題的一些建議。我正在嘗試創建一個生成樹形圖的程序(是的,真正的樹)。這些形狀完全由分支構建而成。爲此,我開始寫一個叫Branch的課。這個想法是,在main.cpp中我創建了一個類Branch的實例,它本身將創建Branch的實例。這繼續進行NUMBER_OF_LEVELS
迭代。C++,同類中的類的實例,類中的父/子結構
main.cpp中:
#include "branch.h"
int main()
{
Branch tree;
return 0;
}
Branch.h:
#include <iostream>
#include <vector>
#include <stdlib.h>
#include <cmath>
using namespace std;
const double NUMBER_OF_LEVELS=4;
static int nodecounter=0;
struct Branch
{
public:
int level;
int nodenumber;
vector<Branch> children;
Branch *parent;
Branch(int lvl,Branch p);
Branch();
static vector<Branch> getAllBranches();
};
Branch.cpp:
現在,如下所述方案的結構
#include "Branch.h"
static vector<Branch> allBranches;
Branch::Branch(int lvl,Branch p)
{
level=lvl;
parent=&p;
nodenumber=nodecounter;
nodecounter++;
allBranches.push_back(*this);
if (lvl>1)
{
children.push_back(Branch(level-1,*this));
}
}
//root
Branch::Branch()
{
level=NUMBER_OF_LEVELS;
nodenumber=nodecounter;
nodecounter++;
allBranches.push_back(*this);
children.push_back(Branch(level-1,*this));
}
vector<Branch> Branch::getAllBranches()
{
return allBranches;
}
現在,這個程序有效,但我希望通過將每個對象存儲在vector
,allBranches
中來跟蹤所有Branch
對象。在程序結束時,allBranches
確實大小爲NUMBER_OF_LEVELS
,因爲它應該是(爲了簡化,每個對象只有一個孩子)。但是,當我嘗試從main.cpp中提取子項或父項時,該程序崩潰時出現錯誤:terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc
我想知道這是否由static
關鍵字的錯誤使用引起的?在C++中創建父/子結構的正確方法是什麼?
瞭解[C++智能指針](http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_pointers) –
您可以查看鏈接列表的工作方式,這是以前的典型用法/下一個機制。 – Djon
這裏的靜態意味着,你將有2個不同的變量:一個用於main.cpp,另一個用於Branch.cpp。您應該在Branch.cpp中使用全局變量,並在Branch.h中聲明'extern int nodecounter;'。 – Elazar