C ++类 - std :: vector类变量在函数后重置

时间:2017-10-24 00:15:39

标签: c++ oop stdvector

我刚刚回到c ++编程并遇到问题。我有一个包含std :: vector的类,如下所示:

class node{

  private:
    std::string name;
    node* parent;
    std::vector<node*> children;

  public:
    node();
    ~node();
    //Setters
    void setName(std::string nodeName);
    void setParent(node* &newParent);
    void addChild(node* child);
    //Getters
    std::string getName();
    node* getParent();
    std::vector<node*> getChildren();
    node* getChild(unsigned index);
};

相关成员函数实现如下:

void node::addChild(node* child){
  children.push_back(child);
  if(children.size() == 2){
    children.erase(children.begin());
  }
}

void node::setParent(node* &newParent){
  parent = newParent;
  if(parent != NULL){
    parent->addChild(this);
  }
}

node* node::getParent(){
  return parent;
}

std::vector<node*> node::getChildren(){
  return children;
}

在另一个文件中,我有一个功能:

void loadTree(std::ifstream &datafile, tree &hierarchicalModel){
    node root();
    node child = readNode(datafile, root);
    root.addChild(&child);
    hierarchicalModel.addRoot(root);
    //I hard coded this in to test, and it prints out exactly what I want.
    std::cout<<hierarchicalModel.getRoot().getChildren()[0]->getName()<<std::endl;
}

这个问题在这里:在我的主文件中,我这样做(hierarchicalModel被声明为全局变量):

void setup(){
    loadTree(dataFile, hierarchicalModel);
    //This will print out exactly what I expect.
    std::cout<<hierachicalModel.getRoot()->getName()<<std::endl;
    //Here is the issue!
    //I hard coded this as well, and it causes a crash. 
    std::cout<<hierarchicalModel.getRoot().getChildren()[0]->getName()<<std::endl;
}

我无法访问我添加它们的函数范围之外的子节点。我以为通过引用传递树对象会处理这个问题。

请帮忙!!如果回答这个问题需要更多信息,请告诉我!!

0 个答案:

没有答案