就业数据资源平台
当前位置:首页 > C++语言程序设计
2012年计算机二级C++练习题:改错题2

改错题
  使用VC6打开考生文件夹下的工程kt7_1,此工程包含一个源程序文件kt7_1.cpp,但该程序运行有问题,请改正程序中的错误,使程序的输出结果如下:
  Constructor1
  Constructor1
  Constructor1
  Destructor
  Constructor2
  Destructor
  x=0
  x=5
  Destructor
  Destructor
  源程序文件kt21_1.cpp清单如下:
  #include
  classB
  {intx;
  public:
  B(){x=0;cout<<"Constructor1"<<ENDL;}< p=""></ENDL;}<>
  B(inti){x=i;cout<<"Constructor2"<<ENDL;}< p=""></ENDL;}<>
  ~B(){cout<<"Destructor"<<ENDL;}< p=""></ENDL;}<>
  /**********found**********/
  ~B(inti){cout<<I<<"BEDESTRUCTOR"<<ENDL;}< p=""></I<<"BEDESTRUCTOR"<<ENDL;}<>
  voidprint(){cout<<"x="<<X<<ENDL;}};< p=""></X<<ENDL;}};<>
  voidmain()
  {B*ptr;
  ptr=newB[2];
  /**********found**********/
  ptr[0]=B(0);
  ptr[1]=B(5);
  /**********found**********/
  for(inti=0;i<2;)
  ptr[i].print();
  delete[]ptr;}
【参考答案】
  (1)将~B(int i){cout<<I<<" p="" be="" Destructor?<<endl;}删除<=""></I<<">
  (2)将ptr[0]=B(0);改为:ptr[0]=B();
  (3)将for (int i=0;i<2;)改为:for(int i=0;i<2;i++)
  B(inti){x=i;cout<<"Constructor2"<<ENDL;}< p=""></ENDL;}<>
  ~B(){cout<<"Destructor"<<ENDL;}< p=""></ENDL;}<>
  /**********found**********/
  ~B(inti){cout<<I<<"BEDESTRUCTOR"<<ENDL;}< p=""></I<<"BEDESTRUCTOR"<<ENDL;}<>
  voidprint(){cout<<"x="<<X<<ENDL;}};< p=""></X<<ENDL;}};<>
  voidmain()
  {B*ptr;
  ptr=newB[2];
  /**********found**********/
  ptr[0]=B(0);
  ptr[1]=B(5);
  /**********found**********/
  for(inti=0;i<2;)
  ptr[i].print();
  delete[]ptr;}
【试题解析】
  本题主要考查对文件相关操作的熟练程度。首先定义文件流类的变量,然后使用该对象的open方法打开一个文件,接着使用while循环和getch方法每次读入一个字符并统计字符个数,最后使用close方法关闭文件,返回i值。
就业数据资源平台