2013-06-01 62 views
1

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

现在,这个程序有效,但我希望通过将每个对象存储在vectorallBranches中来跟踪所有Branch对象。在程序结束时,allBranches确实大小为NUMBER_OF_LEVELS,因为它应该是(为了简化,每个对象只有一个孩子)。但是,当我尝试从main.cpp中提取子项或父项时,该程序崩溃时出现错误:terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

我想知道这是否由static关键字的错误使用引起的?在C++中创建父/子结构的正确方法是什么?

+1

了解[C++智能指针](http://en.wikipedia.org/wiki/Smart_pointer#C.2B.2B_smart_pointers) –

+0

您可以查看链接列表的工作方式,这是以前的典型用法/下一个机制。 – Djon

+0

这里的静态意味着,你将有2个不同的变量:一个用于main.cpp,另一个用于Branch.cpp。您应该在Branch.cpp中使用全局变量,并在Branch.h中声明'extern int nodecounter;'。 – Elazar

回答

0

你有一吨的问题,前几个我发现:

    在头文件
  • 静态变量:不太可能要侵扰每个TU具有鲜明的副本
  • 父指针的结构不任何处理和结构;存储在一个向量中:风险太大,最终导致悬挂指针。在添加更多项目时,指向矢量中的东西无效!
  • 一个很奇怪的构造函数,通过值使用相同类型
  • 父指针设置为发送作为参数的临时副本的地址:显然你的意思是在一个指针传递给一些稳定节点

这足以搅局

小事:

  • 在头文件使用指令 - 限制那些.cpp文件
  • 后增无正当理由

并不意味着要全面