问答题
请使用VC6或使用[答题]菜单打开考生文件夹pmj3下的工程proj3,其中包含主程序文件main.cpp和用户定义的头文件Array.h,整个程序包含有类Array的定义和主函数main的定义。请把主程序文件中的Array类的成员函数Contrary()的定义补充完整,经补充后运行程序,得到的输出结果应该是:
58
5, 4, 3, 2, 1
0, 0, 8.4, 5.6, 4.5, 3.4, 2.3, 1.2
注意:只允许在“//********333********”和“//********666********”之间填写内容,不允许修改其他任何地方的内容。
//Array.h
#include <iostream>
using namespace std;
template<class Type, int m>
class Array { //数组类
public:
Array(Type b[], int mm) { //构造函数
for(int i=0; i<m; i++)
if(i <mm) a[i] =b[i];
else a[i] =0;
}
void Contrary();
//交换数组a中前后位置对称的元素的值
int Length() const{ return m;}
//返回数组长度
Type operator [] (int i)const {
//下标运算符重载为成员函数
if(i<0 ||i>=m)
{cout<<"下标越界"<<endl; exit(1);)
return a[i];
}
private:
Type a[m];
};
void writeToFile(const char * );
//不用考虑此语句的作用
//main.cpp
#include"Array.h"
//交换数组a中前后位置对称的元素的值
template <class Type, int m>
void Array <Type, m >::Contrary ()
//补充函数体
//********333********
//********666********
}
int main(){
int sl[5] ={1, 2, 3, 4, 5};
double s216] = {1.2, 2.3, 3.4, 4.5, 5.6, 8.4};
Array<int, 5> d1(s1,5);
Array<double, 8> d2(s2,6);
int i;
d1.Contrary(); d2.Contrary();
cout <<d1.Length () <<" <<d2. Length ()<<endl;
for(i=0; i<4; i++)
cout <<d1[i] <<",";
cout <<d1[4] <<endl;
for(i=0; i<7; i++)
cout <<d2[i] <<",";
cout <<d2 [7] <<endl;
writeToFile ("");
//不用考虑此语句的作用
return 0;
}
【参考答案】
for(int i=0, j=m-1; i<j; i++, j--) {//i从0开始自加,j从数组最一位开始自减,条件......
(↓↓↓ 点击下方‘点击查看答案’看完整答案、解析 ↓↓↓)