问答题
请使用VC6或使用【答题】菜单打开考生文件夹pmj2下的工程pmj2。其中有向量基类VectorBase、向量类Vector和零向量类ZemVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为:(1,2,3,4,5) (0,0,0,0,0,0) 注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。#include<ioStream>using namespace std;class VectorBase{ //向量基类,一个抽象类 int len;public: VectorBase(int len):len(1en){) int length()const{return len;)//向量长度,即向量中元素的个数 virtual double getElement(int i)const:0;//取第i个元素的值 virtual double sum()const=0;//求所有元素的和 void show()const{//显示向量中所有元素 cout<<”(”; for(int i=0;i<length()一1;i++) cout<<getElement(i)<<”,”; //**********found********** cout<<__________<<”)”<<endl;//显示最后一个元素 } }; class Vector:public VectorBase{ //向量类 double*val ;public: Vector(int len,double v[]=NULL):VectorBase(1en){ val=new double[len]; for(int i=0;i<len; i++)val[i]=(v==NULL?0.0:v[i]); } //**********found********** Vector(){_______;)double getElement(int index)const{return val[index];) double sum()const{. double S=0.0; //**********found********** for(int i=0;i<length();i++)______; return S; } }; class ZeroVector:public VectorBase{ //零向量类 public: ZeroVector(int len): VectorBase(len){) //**********found********** double getElement(int index)const{_____;) double sum()const{return 0.0;)};int main(){ VeCtOrBaSe*V; double d[]={1,2,3,4,5}; V=new Vector(5,d); v一>show(); delete V; v=new ZeroVector(6); v一>show(); delete V; return 0;}
【正确答案】正确答案:(1)getElement(length()一1) (2)delete[]val (3)s+=val[i] (4)return 0.0:
【答案解析】解析:(1)主要考查考生对成员函数的掌握,题目要求显示最后—个元素。前面有纯虚函数virtual double getElement(int i)const=0,因此可以直接调用getElement函数来取得最后一个元素,注意最后—个元素位置是Ungth()一1而不是Length()。 (2)主要考查考生对析构函数的掌握,前面定义了类的私有成员*val,因此析构函数要释放val,使用delete语句完成。 (3)主要考查考生对for循环的掌握,由函数名doublesum()const可知,该函数要求元素之和,for循环语句的作用是遍历整个数组,在此使用语句S+=val[i]完成程序。 (4)主要考查考生对成员函数的掌握,由该类的注释:零向量类,可以了解到该类的元素都为零,因此无论要取第几个元素都返回0,由于数据类型为double,所以为return0.0。