我是C ++的新手,正在寻找有关以下问题的建议。我正在尝试创建一个生成树形状的程序(是的,真实的树)。这些形状完全由分支构成。为此,我开始编写一个名为Branch的类。这个想法是在main.cpp中,我创建了一个类Branch的实例,该类本身将创建Branch的实例。在NUMBER_OF_LEVELS迭代中继续进行。

目前,该程序的结构如下:

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


现在,该程序可以工作了,但我想通过将每个对象存储在Branchvector中来跟踪所有allBranches对象。在程序结束时,allBranches的大小确实应为NUMBER_OF_LEVELS(为简单起见,每个对象只有一个孩子)。但是,当我尝试从main.cpp中提取子项或父项时,程序崩溃,显示为错误:terminate called after throwing an instance of 'std::bad_alloc' what(): std::bad_alloc

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

最佳答案

您遇到了很多问题,我发现了头几个问题:


头文件中的静态变量:您极不可能用不同的副本感染每个TU
结构中的父指针,无需任何处理和结构;存储在向量中:风险太大,以至于指针悬空。添加更多项目时,指向向量中内容的指针将失效!
一个非常奇怪的ctor,其值类型相同
父指针设置为作为参数发送的临时副本的地址:显然,您的意图是将指针传递给某个稳定节点


够了

小事:


在头文件中使用指令-将那些限制为.cpp文件
后增量使用时没有充分的理由


这份清单并不意味着全面

10-08 07:33
查看更多