请使用“答题”菜单或使用VC6菜单打开考生文件夹pro
请使用“答题”菜单或使用VC6菜单打开考生文件夹proj2下的工程 proj2。此工程包含一个程序文件 main.cpp,其中有日期类Date、人员 类Person以及排序函数sortByAge和主函数main的定义。请在程序中的横 线处填写适当的代码,然后删除横线,以实现该程序。此程序的正确 输出结果应为:
排序前:
张三 男 出生日期:1978年4月20日
王五 女 出生日期:1965年8月3日
杨六 女 出生日期:1965年9月5日
李四 男 出生日期:1973年5月30日
排序后:
张三 男 出生日期:1978年4月20日
李四 男 出生日期:1973年5月30日
杨六 女 出生日期:1965年9月5日
王五 女 出生日期:1965年8月3日
注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不能删除或移动“//**********found**********”。
源程序如下:
# 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]; // 姓名
bool is_male; // 性别,为 true 时表示男性
Date birth_date; // 出生日期
public:
Person(char * name, bool is_male, Date birth_date)
//**********found**********
strcpy(this -> name, _________);
}
const char * getName()const{ return name; }
bool isMale()const{ return is_male; }
Date getBirthdate()const{ return birth_date; }
int compareAge(const Person &p)const{
//比较两个人的年龄,返回正数、0或负数,分别表示大于、等于和小于
int n;
n = p.birth_data.getYear() - birth_data.getYear();
if( n != 0 ) return n ;
//**********found**********
___________________________
if( n != 0 ) return n ;
return p.birth_data.getDay() - birth_data.getDay();
}
void show(){
cout<<endl;
cout<<name<<' '; //显示姓名
//**********found**********
<< ___________________ //显示性别(“男”或“女”,双引号内不含空格)
<<"出生日期" //显示出生日期
<<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){
//**********found**********
Person p = ______________________;
ps[m] = ps[i];
ps[i] = p;
}
}
}
int main(){
Person staff[] = {
Person("张三", true, Date(1978, 4, 20)),
Person("王五", false, Date(1965,8,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;
return 0;
}答案
第1空:name
第2空:n=P.birth_data.getMonth()-birth_data.get- Month(); / n=birth_data.getMonth()+P.birth_data.get- Month();
第3空:(is_male?”男”: ”女”)
第4空:ps[m];
解析
第1处是将this->name复制到name上,所以填name。
第2处是比较两个人的出生的月份的大小,根据上下几句的程序可以推断出该处的格式应为n=p.birth_data.getMonth()_birth_data.getMonth()
或n=-birth_data.getMonth()+p.birth_data.getMonth()。
第3处根据提示显示出性别,所以应填(is_male?“男”:“女”)。
第4处是将ps[m]的值与ps[i]的值互换,所以应该填ps[m]。