我对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