【发布时间】:2020-07-17 12:32:40
【问题描述】:
我正在尝试实现家谱。我的类Person 和Tree 定义如下:
文件FamilyTree.hpp:
using namespace std;
#include <string>
namespace family{
class Person{
public:
string name;
Person* mother;
Person* father;
Person(string name);
};
class Tree{
public:
Person* root;
Tree(string name);
Tree& addFather(string name1, string name2);
Tree addMother(string name1, string name2);
void display();
string relation(string name);
string find(string name);
void remove(string name);
};
};
文件FamilyTree.cpp:
#include "FamilyTree.hpp"
#include <string>
#include <iostream>
using namespace family;
// FUNCTIONS
Person& findPerson(Person& root, string child_name){
if (root.name.compare(child_name) != 0)
{
cout<<root.name<<":1"<<endl;
findPerson(*root.father, child_name);
}
else if(root.name.compare(child_name) == 0){
cout<<root.name<<":2"<<endl;
return root;
}else{
cout<<"not found!!!"<<endl;
Person p("no found");
return p;
}
}
// PERSON
family::Person::Person(string person_name){
name = person_name;
father = nullptr;
mother = nullptr;
};
// TREE
family::Tree::Tree(string name){
root = new Person(name);
};
family::Tree& Tree::addFather(string child, string father){
Person& child_found = findPerson(*root, child);
//cout<<"child_found.name:"<<child_found.name<<endl;
child_found.father = new Person(father);
return *this;
};
family::Tree family::Tree::addMother(string name1, string name2){return Tree("");};
void family::Tree::display(){};
string family::Tree::relation(string name){return "";};
string family::Tree::find(string name){return "";};
void family::Tree::remove(string name){};
int main(){
Tree t("X");
t.addFather("X", "Y");
t.addFather("Y","Z");
return 0;
}
我从addFather() 函数开始:
addFather("child", "new father") 为现有孩子添加新父亲。
我使用findPerson() 函数递归地实现了它,该函数返回子对象的Person 对象和addFather() func 创建新的Person 并将其初始化为找到的子对象。
添加 2 个父亲后,出现 Illegal instruction (core dumped) 错误,应该是什么问题?
【问题讨论】:
标签: c++ compiler-errors core coredump