【发布时间】:2020-04-10 11:45:00
【问题描述】:
我试图用人来实现二叉树。 任何人都有父亲和母亲。 在我的 main() 函数中,它运行良好,直到我将人添加到我的第一个“X”的父亲。 我的 main 在第 4 次 addFather("Y","F") 调用中出现 Aborted (core dumped) 错误,我无法意识到我的错。
Person& findPerson(Person* root, string child_name){
if(root == nullptr) throw exception();
else if(root->name.compare(child_name) == 0) return *root;
else{
if(root->father == nullptr)return findPerson(root->mother, child_name);
else if(root->mother == nullptr)return findPerson(root->father, child_name);
else {
return findPerson(root->mother, child_name);
return findPerson(root->father, child_name);
}
}
}
family::Person::Person(string person_name){
name = person_name;
father = nullptr;
mother = nullptr;
};
family::Person::Person(string person_name, bool is_male){
name = person_name;
father = nullptr;
mother = nullptr;
isMale = is_male;
};
// TREE
family::Tree::Tree(string name){
root = new Person(name);
};
family::Tree& Tree::addFather(string child, string father){
Person& child_found = findPerson(root, child);
Person* f = new Person(father, true);
child_found.father = f;
return *this;
};
family::Tree& family::Tree::addMother(string child, string mother){
Person& child_found = findPerson(root, child);
Person* f = new Person(mother, false);
child_found.mother = f;
return *this;
};
int main(){
Tree t("X");
t.addFather("X","Y");
t.addMother("X", "Z");
t.addFather("Z", "W");
t.addFather("Y","F");
return 0;
}
【问题讨论】:
-
请注意,一旦函数返回,它就会退出。你有
return findPerson(root->mother, child_name);然后return findPerson(root->father, child_name);在连续的行上。第二个 return 永远不会执行。 -
是的,在 findPerson() 中
-
那么我怎样才能让其中两个执行呢?我可能会导致一些递归失败。
-
我认为您应该更改签名以返回指针而不是引用。然后你可以比较返回到 nullptr 的指针。在这种情况下,您可能希望摆脱
if(root == nullptr) throw exception();并返回 nullptr if root == nullptr -
实际上您的解决方案有效!我的错误的解释是什么?
标签: c++ error-handling tree