问答题
请使用“答题”菜单或从VC6中打开考生文件夹proj1下的工程proj1。此工程包含了类Pets(“宠物”)和主函数main的定义。程序中位于每个//ERRO************found************下的语句行有错,请加以改正。改正后程序的输出结果是: Name: sonny Type: dog Name: John Type: dog Name: Danny Type: cat Name: John Type: dog 注意:只能修改每个//ERROR************found************下的那一行,不要改动程序中的其他内容。 //源程序 #include <iostream> using namespace std; enum Pets_typedog,cat,bird,fish; class Pets private: char*name: Pets_type type; public: Pets(const char*name="sonny",Pets_type type=dog); Pets& operator=(const Pets &s); ~Pets(); void show() const; ; Pets::Pets(const char*name,Pets_type type) //构造函数 this->name=new char[strlen(name)+1]; strcpy(this->name,name); //ERROR************found************ type=type; Pets::~Pets() //析构函数,释放name所指向的字符串 //ERROR************found************ name='/0': Pets&Pets::operator=(const Pets &s) if(&s==this) return*this; //确保不要向自身赋值 delete[]name; name=new char[strlen(s.name)+1]; //ERROR************found************ strcpy(s.name,this->name); type=S.type; return*this: void Pets::show() const couL<<"Name:"<<name<<"Type:"; switch(type) case dog: cout<<"dog";break; case cat: cout<<"cat";break; case bird: cout<<"bird";break; case fish: cout<<"fish";break; cout<<endl; int main() Pets mypet1,mypet2("John",dog); Pets youpet("Danny",cat); mypet1.show(); mypet2.show(); youpet.show(); youpet=mypet2; youpet.show(); return 0:
【正确答案】 1)this->type=type; 2)delete[]name; 3)strcpy(this->name,s.name);
【答案解析】 [解析] 1)将实参传递进来的type值赋给本对象的type,应该在本对象前加上this指针。 2)析构函数的功能就是执行清理任务,将分配给对象的内存释放,所以在析构函数中应该将在构造函数中生成的数组释放。 3)数组字符复制,应该是将name的内容复制给本对象的name,而不是相反。
提交答案
关闭