请使用V05或使用【答题】菜单打开考生文件夹pmj1下的工程pmj1,此工程中包含了类Pets(“宠物”)和主函数main的定义。程序中位于每个“//ERROR****found****”之后的一行语句有错误,请加以改正。改正后程序的输出结果应为: Nam

admin2016-06-12  22

问题 请使用V05或使用【答题】菜单打开考生文件夹pmj1下的工程pmj1,此工程中包含了类Pets(“宠物”)和主函数main的定义。程序中位于每个“//ERROR****found****”之后的一行语句有错误,请加以改正。改正后程序的输出结果应为:
Name:sonny Type:dog
Name:John Type:dog
Nine:Danny Type:cat
Name:John Type:dog
注意:只修改每个“//ERROR****found****”下的那一行,不要改动程序中的其他内容。
#include
using namespace std;
enum Pets type{dog,cat,bird,fish);
class Pets{
private:
  char*name;
  Petstyp;type  e
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(this一>name,name);
  type=S.type;
  return*this  ;
}
void Pets::show()const
{
cout<<“Name:”<switch(type)
{
case dog:cout<<“dog”;break;
case cat:cout<<“cat”;break;
case bird:cout<<“bird”;break;
case fish:cout<<“fish”;break;
}
cout<}
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);

解析 主要考查的是Pets类,其中涉及enum类型、动态数组、构造函数、运算符重载、析构函数和const函数。本题程序很长,涉及的函数类型较多,但考查的内容较简单,只要注意细节便可答对此题。
【解题思路】
(1)主要考查考生对构造函数的掌握情况,因为形参名和类的私有成员名称都是type,为了避免混淆,所以规定类的私有成员使用this指针调用,即:this一>type=type;。
(2)主要考查考生对析构函数的掌握情况,题目中要求,释放name所指向的字符串。要释放name指针用delete语句,即delete[]name;。
(3)主要考查考生对sUcpy函数的掌握情况,strcpy函数的形参为两个字符串,而name为指向字符串的指针,因此使用语句:strcpy(this一>name,s.name);。
【解题宝典】
主要考查考生对构造函数、析构函数和strcpy()函数的掌握,构造函数中当类的私有成员和形参名称相同时,为了区别类的成员要调用this指针来区分。析构函数必须要用delete语句释放指针。
转载请注明原文地址:https://kaotiyun.com/show/SYNp777K
0

最新回复(0)