用c++编写家谱的设计与实现
时间: 2023-08-15 21:06:24 浏览: 71
为了实现家谱的设计与实现,可以采用面向对象的编程思想,用C++编写程序,以下是一个简单的家谱示例:
```C++
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Person {
public:
Person(string n, int a) : name(n), age(a) {}
string getName() { return name; }
int getAge() { return age; }
void addChild(Person* child) { children.push_back(child); }
void printChildren() {
for (int i = 0; i < children.size(); i++) {
cout << children[i]->getName() << endl;
}
}
private:
string name;
int age;
vector<Person*> children;
};
int main() {
Person* grandpa = new Person("Grandpa", 80);
Person* father = new Person("Father", 50);
Person* uncle = new Person("Uncle", 55);
Person* son = new Person("Son", 20);
Person* daughter = new Person("Daughter", 18);
grandpa->addChild(father);
grandpa->addChild(uncle);
father->addChild(son);
father->addChild(daughter);
cout << grandpa->getName() << "'s children: " << endl;
grandpa->printChildren();
cout << father->getName() << "'s children: " << endl;
father->printChildren();
return 0;
}
```
在这个家谱示例中,`Person`类表示一个人,包含姓名、年龄和孩子等信息。`addChild`函数用于添加一个孩子到当前人的孩子列表中,`printChildren`函数用于打印当前人的所有孩子的姓名。在`main`函数中,我们创建了一个家族树,并打印了每个人的孩子列表。
当然,这只是一个简单的示例,实际的家谱可能包含更多的信息和功能,需要根据实际需求进行设计和实现。