问答题 请使用VC6或使用[答题]菜单打开考生文件夹proj3下的工程proj3,其中包含源程序文件main.cpp和用户定义的头文件Array.h,整个程序包含有类Array的定义和主函数main的定义。请把主程序文件中的Array类的成员函数MinTwo()的定义补充完整,经修改后运行程序,得到的输出结果应为: 8 29,20,33,12,18,66,25,14 12.14 注意:只允许在“//********333********”和“//********666********”之间填写内容,不允许修改其他任何地方的内容。 //Arry. h #include <iostream> #include <cstdlib> using namespaee std; template <class Type> class Array { //数组类 public: Array(Type b[], int mm): size (mm) { //构造函数 if(size<2) {cout <<"数组长度太小, 退出运行!"; exit(1); } a=new Type[ size]; for(int i=0; i<size; i++) a[i]=b[i]; } ~Array() {delete [ ]a;} //析构 void MinTwo (Type& x1, Type& x2)const; //由x1和x2带回数组a中最小的两个值 int Length() const{ return size; } Type operator [] (int i)const { //下标运算符重载为成员函数 if (i<0 || i>=size) {cout<<"下标越界!" <<endl; exit (1);} return a[i]; } private: Type * a; int size; }; void writeToFile(const char * ); //不用考虑此语句的作用 //main. cpp #include "Array. h" template <class Type> void Array <Type>::MinTwo (Type& x1, Type& x2) const { //补充完整函数体的内容 a[0] <=a[1]? (x1=a[0], x2=a[1]):(x1=a[1], x2=a[0]); //******** 333******** //******** 666******** } int main () { int s1[8]={29, 20, 33, 12, 18, 66, 25, 14}; Array<int> d1 (s1, 8); int i, a, b; d1.MinTwo (a, b); cout <<d1.Length() <<endl; for(i=0; i<7; i++) cout <<d1[i]<<", "; cout <<d1[7] <<endl; cout <<a<<", "<<b<<endl; writeToFile (""); return 0; }
【正确答案】for(int i=2; i<size; i++) //i从2到size-1遍历数组
if(x2>a[i]) //如果x2大于a[i]
if(x1>a[i]) //如果x1,大于a[i]
{
x2=x1; //把x1赋值给x2
x1=a[i]; //a[i]赋值给x1
)
else //否则
{
x2=a[i]; //a[i]赋值给x2
}
【答案解析】[考点] 本题考查Array类,其中涉及构造函数、析构函数和const函数。 [解析] 主要考查考生对数组的掌握,函数要求由a和b带回数组a中最小的两个值。使用for循环遍历数组,使用条件语句对数组元素进行比较操作,并把最小值赋给a和b。