操作题
请使用菜单命令或直接使用VC6打开下的工程proj1,其中有“MP3播放器”类MP3Player和主函数main的定义。程序中位于每个//ERROR **********found**********下的语句行有错误,请加以更正。更正后程序的输出应该是:
天籁-1
黑色
注意:只能修改每个//ERROR ***********found***********下的那一行,不要改动程序中的其他内容。
#include<iostream>
#include<iostream>
using namespace std;
class MP3Player { //“MP3播放器”类
char*type;//型号
char*color;//颜色
public:
//ERROR *********found*********
MP3Player(const char*ty=NULL, const char*co) {
//ERROR *********found*********
if(ty=NULL)
type=NULL;
else{
type=new ehar[stden(ty)+1];
strcpy(type, ty);
}
if(co==NULL)
color=NULL;
else{
color=new char[strlen(co)+1];
strcpy(color, co);
}
}
~MP3Player(){
if(type) delete[]type;
//ERROR *********found*********
if(color) delete color;
}
const char *getType()const {return type;}
const char *getColor()const {return color;}
};
int main(){
MP3Piayer myplayer(“天籁-1”, “黑色”);
cout<<myplayer.getType()<<endl;
cout<<myplayer.getColor()<<endl;
return 0;
}
【正确答案】(1)MP3Player(const char*ty=NULL, const char*co=NULL){ 或MP3Player(const char*ty, const char*co){ (2)if(ty==NULL) (3)if(color) delete[]color; 答案考生文件夹
【答案解析】本题考查MP3Player类,其中涉及构造函数的参数默认值、相等运算符与赋值运算符的区别、动态分配内存的释放。 (1)主要考查考生对函数参数的默认值的掌握,C++中的函数可以提供默认实参,如果一个形参具有默认实参,那么它之后的所有形参都必须有默认实参,题目中ty提供了默认实参,所以co也必须提供默认实参,或者将ty的默认实参去掉。 (2)主要考查考生对相等运算符与赋值运算符区别的掌握,题意是判断指针ty是否为NULL,而不是将ty赋值为NULL,修改赋值运算符为相等运算符。 (3)主要考查动态分配内存的释放,动态分配的内存在释放时,new分配的内存需要使用delete释放,而new[]分配的内存需要使用delete[]。