应用题
请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中包含了日期类Date、人员类Person及排序函数sortByAge和主函数main的定义。其中Person的成员函数compareAge的功能是:将当前Person对象和参数Person对象进行比较,若前者的年龄大于后者的年龄,则返回一个正数;若前者的年龄小于后者的年龄,则返回一个负数;若年龄相同则返回0。注意,出生日期越大,年龄越小。请编写成员函数compareAge。在main函数中给出了一组测试数据,此时程序的正确输出结果应为:
按年龄排序
排序前:
张三 男 出生日期:1978年4月20日
王五 女 出生日期:1965年6月3日
杨六 女 出生日期:1965年9月5日
李四 男 出生日期:1973年5月30日
排序后:
张三 男 出生日期:1978年4月20日
李四 男 出生日期:1973年5月30日
杨六 女 出生日期:1965年9月5日
王五 女 出生日期:1965年6月3日
要求:
补充编制的内容写在“//********333********”与“//********666********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数WriteToFile已经编译为obj文件,并且在本程序中调用。
//Person.h
#include <iostream>
using namespace std;
class Date{ //日期类
int year, month, day; //年、月、日
public:
Date(int year, int month, int day): year(year), month(month), day(day){}
int getYear() const { return year; }
int getMonth () const { return month; }
int getDay () const { return day; }
};
class Person { //人员类
char name[14]; //姓名
boom is_male; //性别,为true时表示男性
Date birth_date; //出生日期
public:
Person (char * name, bool is_male, Date birth_date);
const char * getName () const { return name; }
bool isMale()const{ return is_male; }
Date getBirthdate () const { return birth_date; }
int compareAge (const Person &p) const;
void show () const;
};
void sortByAge(Personps[], int size);
void writeToFile(char * );
//main.cpp
#include'Person.h'
Person::Person(char * name, bool is_male, Date birth_date): is_male (is_male), birth_date (birth_date) {
strcpy(this->name, name);
}
int Person::compareAge(const Person &p) const {
//******** 333********
//******** 666********
}
void Person::show () const {
cout << endl;
cout << name << ' //显示姓名
<< (is_male? '男' : '女') //显示性别('男'或'女')
<<'出生日期:' //显示出生日期
<<birth_date.getYear () << '年'
<<birth_date.getMonth() <<'月'
<<birth_date.getDay() <<'日';
}
void sortByAge(Person ps[], int size)
{//对人员数组按年龄由小到大的顺序排序
for(int i=0; i<size-1; i++) { //采用选择排序算法
int m=i;
for (int j=i+1; j<size; j++)
if (ps[j].compareAge (ps[m])<0)
m=j;
if (m>i) {
Person p=ps[m];
ps[m]=ps[i];
ps[i]=p;
}
}
}
int main() {
Person staff[] = {
Person ('张三', true, Date (1978, 4, 20)),
Person ('王五', false, Date (1965, 6, 3)),
Person('杨六', false, Date (1965, 9, 5)),
Person ('李四', true, Date (1973, 5, 30))
};
const int size = sizeof (staff)/sizeof(staff[0]);
int i;
cout << '按年龄排序' << endl <<'排序前:';
for(i=0; i<size; i++) staff[i]. show ();
sortByAge (staff, size);
cout << endl << endl << '排序后:';
for(i=0; i<size; i++) staff[i]. show ();
cout << endl;
writeToFile ('');
return 0;
}