2013-06-01 61 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文件
  • 後增無正當理由

並不意味着要全面