爲了使廣大考生在備戰計算機等級考試時,更快的掌握相應知識點,下面是小編搜索整理的計算機二級C++練習題:改錯題,供參考練習,預祝考生們考出自己理想的成績!
計算機二級C++練習題:改錯題
使用VC6打開考生文件夾下的`工程kt7_1,此工程包含一個源程序文件kt7_,但該程序運行有問題,請改正程序中的錯誤,使程序的輸出結果如下:
Constructor1
Constructor1
Constructor1
Destructor
Constructor2
Destructor
x=0
x=5
Destructor
Destructor
源程序文件kt21_清單如下:
#include
classB
{intx;
public:
B(){x=0;cout<<"Constructor1"<<ENDL;}
B(inti){x=i;cout<<"Constructor2"<<ENDL;}
~B(){cout<<"Destructor"<<ENDL;}
/**********found**********/
~B(inti){cout<<I<<"BEDESTRUCTOR"<<ENDL;}
voidprint(){cout<<"x="<<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]t();
[]ptr;}
【參考答案】
(1)將~B(inti){cout<<I<<"p=""be=">
(2)將ptr[0]=B(0);改爲:ptr[0]=B();
(3)將for(inti=0;i<2;)改爲:for(inti=0;i<2;i++)
B(inti){x=i;cout<<"Constructor2"<<ENDL;}
~B(){cout<<"Destructor"<<ENDL;}
/**********found**********/
~B(inti){cout<<I<<"BEDESTRUCTOR"<<ENDL;}
voidprint(){cout<<"x="<<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]t();
[]ptr;}
【試題解析】
本題主要考查對文件相關操作的熟練程度。首先定義文件流類的變量,然後使用該對象的open方法打開一個文件,接着使用while循環和getch方法每次讀入一個字符並統計字符個數,最後使用close方法關閉文件,返回i值。