用c++写一个家谱管理系统
时间: 2023-06-13 17:07:44 浏览: 108
精选_基于C++实现的家谱管理系统_源码打包
下面是一个简单的家谱管理系统的 C++ 代码示例:
```cpp
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person {
public:
Person(string name, string gender, int age) {
this->name = name;
this->gender = gender;
this->age = age;
}
string getName() {
return name;
}
string getGender() {
return gender;
}
int getAge() {
return age;
}
void display() {
cout << "Name: " << name << endl;
cout << "Gender: " << gender << endl;
cout << "Age: " << age << endl;
}
private:
string name;
string gender;
int age;
};
class FamilyTree {
public:
FamilyTree(string rootName, string rootGender, int rootAge) {
root = new Person(rootName, rootGender, rootAge);
}
~FamilyTree() {
delete root;
}
void addChild(string parentName, string childName, string gender, int age) {
Person *parent = findPerson(parentName);
if (parent == nullptr) {
cout << parentName << " is not found in the family tree." << endl;
return;
}
parent->display();
cout << "has a child named " << childName << endl;
Person *child = new Person(childName, gender, age);
children.push_back(child);
}
void display() {
cout << "Family Tree:" << endl;
root->display();
for (int i = 0; i < children.size(); i++) {
children[i]->display();
}
}
private:
Person *root;
vector<Person *> children;
Person *findPerson(string name) {
if (root->getName() == name) {
return root;
}
for (int i = 0; i < children.size(); i++) {
if (children[i]->getName() == name) {
return children[i];
}
}
return nullptr;
}
};
int main() {
FamilyTree *familyTree = new FamilyTree("Jack", "Male", 50);
familyTree->addChild("Jack", "Tom", "Male", 25);
familyTree->addChild("Jack", "Lily", "Female", 22);
familyTree->addChild("Tom", "Jerry", "Male", 2);
familyTree->display();
delete familyTree;
return 0;
}
```
这个程序实现了一个简单的家谱管理系统,包含了两个类:`Person` 和 `FamilyTree`。
`Person` 类包含了一个人的基本信息,包括姓名、性别和年龄。
`FamilyTree` 类实现了家谱管理系统的功能,包括添加子女和显示家谱等。
在 `main` 函数中,我们创建一个 `FamilyTree` 对象,并添加一些人物信息,最后调用 `display` 方法显示整个家谱。
阅读全文