请使用“答题”菜单或使用VC6打开考生文件夹proj2下的工程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 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(len)
val=new double[len];
for(int i=0; i<len, i++) val[i]=(v==NULL0.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)cout<<getElement(len-l)<<")"<<endl;
2)~Vector(){delete val;}
3)for(int i=0;i<length();i++)s=s+val[i];
4)double getElement(int index) const{ return 0.0;}
解析:1)向量的最后一个元素长度应该是len-1,还需要打印")"和换行。
2)析构函数用于释放数组,故此处填写delete val,注意val后面不再需要跟[]。
3)求和函数对向量求和,将向量中的每个元素累加赋值给s,所以应该是s=s+val[i]。
4)对零向量取元素,因为零向量每个元素都为0,所以直接返回值为0.0即可。