请使用VC6或使用【答题】菜单打开考生文件夹proj2下的工程proj2。其中有向量基类VectorBase、向量类Vector和零向量类ZeroVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为: (1.2,

admin2016-08-19  42

问题 请使用VC6或使用【答题】菜单打开考生文件夹proj2下的工程proj2。其中有向量基类VectorBase、向量类Vector和零向量类ZeroVector的定义。请在横线处填写适当的代码并删除横线,以实现上述类定义。该程序正确输出结果应为:
(1.2,3,4.5)
    (0,0,0,0,0,0)
    注意:只能在横线处填写适当的代码,不要改动程序中的其他内容,也不要删除或移动“//****found****”。
1   {}include
2   using namespace std;
3     class VectorBase{//向量基类,一个抽象类
4   int len;
5   public:
6  VectorBase(int len):len(1en){]
7   int length()const{return len;}//向量长度,即向量中元素的个数
8    virtual double getElement(int  i)const=0;//取第i个元素的值
9    virtual double sum()const=0;//求所有元素的和
10  void show()const{//显示向量中所有元素
11   cout<<"(";
12    for(int i=0;i13    cout<14    //**********found**********
15    cout<<_______<<")"<16    }
17  };
18    class Vector:public VectorBase{//向量类
19    double*val;
20   public:
21    Vector(int fen,double v[]=NULL):VectorBase(fen){
22    val=new double[len];
23    for(int i=0;i=(v=NULL?0.0:v);
24    }
25    //**********found**********
26    ~Vector(){_____;}
27   double getElement(int index)const{return val[index];}
28    double sum()const{
29    double s=0.0;
30    //**********found**********
31    for(int i=0;i32    return s;
33  }
34  };
35  class ZeroVector:public VectorBase {//零向量类
36  public:
37    ZeroVector(int len):  VectorBase(len){}
38    //**********found**********
39    double getElement(int index)const{_______;}
40  double sum()const{return 0.0 ;}
41   },
42   int main(){
43   VectorBase*v;
44   double d[]={1,2,3,4,5};
45   v=new Vector(5,d);
46   v->show();
47   delete v;
48   v=new ZeroVector(6);
49    v->show();
50   delete v;
51   return 0;
52 }

选项

答案(1)getElement(1ength()-1) (2)delete[]val (3)s+=val[i] (4)return 0.0:

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

最新回复(0)