请打开考生文件夹下的解决方案文件proj2,其中有向量基类VectorBase、向量类Vector和零向量类ZeroVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为: (1,2,3,4,5) (0,0,0,0

admin2018-07-06  18

问题 请打开考生文件夹下的解决方案文件proj2,其中有向量基类VectorBase、向量类Vector和零向量类ZeroVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为:
(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(len){}
int length( )const{returnlen;}
//向量长度,即向量中元素的个数
virtual double getElement(inti)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(len){
val=new double[len];
for(int i=0;i<len;i++)
val=(v==NULL?0.0:v);
}
//*******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{return0.0;
}
};
int main( ){
VectOrBaSe*v;
double d[ ]={1,2,3,4,5};
v=new Vector(5,d);
v->show( );
defete v;
v=new ZeroVector(6);
v->show( );
delete v;
return0;
}

选项

答案(1)getElement(length( )-1) (2)delete[ ]val (3)s+=val[i] (4)return0.0;

解析 (1)主要考查考生对成员函数的掌握,题目要求显示最后一个元素。前面有纯虚函数virtual double getElement(int i)const=0,因此可以直接调用getElement函数来取得最后一个元素,注意最后一个元素位置是Length( )-1而不是Length( )。
(2)主要考查考生对析构函数的掌握,前面定义了类的私有成员*val,因此析构函数要释放val,使用delete语句完成。
(3)主要考查考生对for循环的掌握,由函数名double sum( )const可知,该函数要求元素之和,for循环语句的作用是遍历整个数组,在此使用语句s+=val完成程序。
(4)主要考查考生对成员函数的掌握,由该类的注释:零向量类,可以了解到该类的元素都为零,因此无论要取第几个元素都返回0,由于数据类型为double,所以为return0.0。
转载请注明原文地址:https://kaotiyun.com/show/8AAp777K
0

最新回复(0)