设计一个虚基类Person,派生出父亲类Father、母亲类Mother,间接派生出孩子类Child;其主要数据包括姓、名、年龄,性别,孩子用父亲的姓;要求如下:
- 重载构造函数初始化数据成员;
- 公有成员函数void SetData([形参列表]);//实现数据成员赋值;
- 分别输出数据成员void Display( );
- 设计一个Person对象指针数组,完成初始化;
- 并按照年龄从大到小排序输出,形式如下:
| 姓名 | 年龄 | 性别 | 父亲 | 母亲 |
| 王军 | 49 | 男 | 不详 | 不详 |
| 李丽 | 47 | 女 | 不详 | 不详 |
| 张语 | 35 | 男 | 不详 | 不详 |
| 刘美 | 32 | 女 | 不详 | 不详 |
| 王仪 | 17 | 女 | 王军 | 李丽 |
| 张芊 | 5 | 女 | 张语 | 刘美 |
VS2019环境
#includeusing namespace std; class Person { protected: string sex=" "; int age; string firstname; string lastname; string father; string mother; public: Person() { age = 0; firstname = " "; lastname = " "; father = "不详"; mother = "不详"; }; void SetData(string Sex,int Age,string Firstname,string Lastname); void Display(); int Getage() { return age; } }; void Person::SetData(string Sex, int Age, string Firstname, string Lastname) { sex = Sex; age = Age; firstname = Firstname; lastname = Lastname; } void Person::Display() { cout << "姓名:" << firstname << lastname << " " << "年龄:" << age << " " << "性别:" << sex << " " << "父亲:" << father << " " << "母亲:" << mother << endl; } class Father :public virtual Person { public: Father() :Person() { sex = "男"; } void SetData(int Age, string Firstname, string Lastname) { age = Age; firstname = Firstname; lastname = Lastname; } string Getfirstname() { return firstname; } string Getlastname() { return lastname; } }; class Mother :public virtual Person { public: Mother() :Person() { sex = "女"; } void SetData(int Age, string Firstname, string Lastname) { age = Age; firstname = Firstname; lastname = Lastname; } string Getfirstname() { return firstname; } string Getlastname() { return lastname; } }; class Child :public Father, public Mother { public: Child():Person() {} void SetData(int Age, string Sex, string Lastname,Father &man,Mother &woman) { firstname = man.Getfirstname(); age = Age; sex = Sex; lastname = Lastname; father = man.Getfirstname()+man.Getlastname(); mother= woman.Getfirstname()+woman.Getlastname(); } }; int main() { Person* p; p = new Person[6]; Father f1, f2; Mother m1, m2 ; Child c1, c2; f1.SetData(49, "王","军"); f2.SetData(35, "张", "语"); m1.SetData(47, "李", "丽"); m2.SetData(32, "刘", "美"); c1.SetData(17, "女", "仪", f1, m1); c2.SetData(5, "女", "芊",f2, m2); //p = &f1; p[0]=f1; p[1] = f2; p[2] = m1; p[3] = m2; p[4] = c1; p[5] = c2; for (int i = 0; i < 6; i++) { for (int j = 0; j < 5; j++) { if (p[j].Getage() < p[j + 1].Getage()) { Person q; q = p[j]; p[j] = p[j + 1]; p[j + 1] = q; } } } for (int i = 0; i < 6; i++) { p[i].Display(); } return 0; }



