问答题
请使用VC6或使用【答题】菜单打开考生文件夹proj2下的工程proj2。其中有向量基类VectorBase、向量类Vector和零向量类ZeroVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为:(1.2.3.4,5)(0,0,0,0,0,0)注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。#include<iostream>usingnamespacestd;classVectorBase{//向量基类,一个抽象类intlen;public:VectorBase(intlen):fen(len){}intlength()const{returnlen;}//向量长度,即向量中元素的个数virtualdoublegetElement(inti)const=0;//取第i个元素的值virtualdoublesum()const=0;//求所有元素的和voidshow()const{//显示向量中所有元素cout<<"(";for(inti=0,i<length()-1;i++)cout<<getElement(i)<<",";//**********found**********cout<<________<<")"<<end1;//显示最后一个元素}};classVector:publicVectorBase{//向量类double*val;public:Vector(intlen,doublev[]=NULL):VectorBase(len){val=newdouble[len];for(inti=0;i<len;i++)val[i]=(v==NULL?0.0:v[i]),}//**********found**********~Vector(){________;}doublegetElement(intindex)const{returnval[index];}doublesum()const{doubles=0.0;//**********found**********for(inti=0;i<length();i++)________;returns;}};classZeroVector:publicVectorBase{//零向量类public:ZeroVector(intlen):VectorBase(len){}//**********found**********doublegetElement(intindex)const{________;}doublesum()const{return0.0;}};intmain(){VeCtorBaSe*v;doubled[]={1,2,3,4,5};V=newVector(5,d);v->show();deletev;v=newZeroVector(6);v->show();deleteV;return0,}
【正确答案】正确答案:(1)getElement(length()一1) (2)delete[]val (3)s+=val[i] (4)return0.0;
【答案解析】解析:(1)主要考查考生对成员函数的掌握,题目要求显示最后一个元素。前面有纯虚函数virtualdoublegetElement(inti)const=0,因此可以直接调用getElement函数来取得最后一个元素,注意最后—个元素位置是Length一1而不是Length( )。 (2)主要考查考生对析构函数的掌握,前面定义了类的私有成员*val,因此析构函数要释放val,使用delete语句完成。 (3)主要考查考生对for循环的掌握,由函数名doublesum()const可知,该函数要求元素之和,for循环语句的作用是遍历整个数组,在此使用语句s+=val[i]完成程序。 (4)主要考查考生对成员函数的掌握,由该类的注释:零向量类,可以了解到该类的元素都为零,因此无论要取第几个元素都返回0,由于数据类型为double,所以为retum0.0。