用c++代码写一个家谱管理系统
时间: 2023-06-26 12:04:10 浏览: 123
这里给出一个简单的家谱管理系统的C++代码,基于面向对象的思想,包含了家庭成员的基本信息、家庭成员之间的关系以及一些简单的操作函数。
```
#include<iostream>
#include<string>
#include<vector>
using namespace std;
class Person {
public:
string name;
string gender;
int age;
vector<Person*> children;
Person(string n, string g, int a) :name(n), gender(g), age(a) {}
};
class FamilyTree {
private:
Person* root;
public:
FamilyTree(Person* r) :root(r) {}
void addChild(Person* parent, Person* child);
void deleteChild(Person* parent, Person* child);
void showFamilyTree(Person* root);
};
void FamilyTree::addChild(Person* parent, Person* child) {
parent->children.push_back(child);
}
void FamilyTree::deleteChild(Person* parent, Person* child) {
vector<Person*>::iterator it = parent->children.begin();
while (it != parent->children.end()) {
if (*it == child) {
parent->children.erase(it);
break;
}
it++;
}
}
void FamilyTree::showFamilyTree(Person* root) {
cout << "Name: " << root->name << ", Gender: " << root->gender << ", Age: " << root->age << endl;
if (root->children.empty()) return;
for (auto child : root->children) {
showFamilyTree(child);
}
}
int main() {
// 初始化家庭成员
Person* grandpa = new Person("Grandpa", "Male", 70);
Person* grandma = new Person("Grandma", "Female", 68);
Person* father = new Person("Father", "Male", 45);
Person* mother = new Person("Mother", "Female", 40);
Person* son1 = new Person("Son1", "Male", 20);
Person* son2 = new Person("Son2", "Male", 18);
Person* daughter = new Person("Daughter", "Female", 16);
// 初始化家谱
FamilyTree familyTree(grandpa);
familyTree.addChild(grandpa, grandma);
familyTree.addChild(grandpa, father);
familyTree.addChild(father, mother);
familyTree.addChild(father, son1);
familyTree.addChild(father, son2);
familyTree.addChild(father, daughter);
// 显示家谱
familyTree.showFamilyTree(grandpa);
// 删除一个孩子后再次显示家谱
familyTree.deleteChild(father, son2);
cout << "After deleting Son2: " << endl;
familyTree.showFamilyTree(grandpa);
return 0;
}
```
这个家谱管理系统定义了 `Person` 和 `FamilyTree` 两个类,其中 `Person` 类表示每个家庭成员,包含姓名 `name`、性别 `gender`、年龄 `age` 和子女 `children`。 `FamilyTree` 类表示整个家谱,包含根节点 `root` 和添加子女、删除子女、显示家谱的三个操作函数。在 `main` 中初始化了一些家庭成员和家谱,并通过 `familyTree.showFamilyTree(grandpa)` 显示了整个家谱。
阅读全文