请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程文件proj3。本题创建一个小型字符串类,字符串长度不超过100。程序文件包括proj3.h.proj3.cpp、writeToFile.obj。 补充完成proj3.h,重载复合赋值运算符+=

admin2015-06-27  27

问题 请使用VC6或使用【答题】菜单打开考生文件夹proj3下的工程文件proj3。本题创建一个小型字符串类,字符串长度不超过100。程序文件包括proj3.h.proj3.cpp、writeToFile.obj。
补充完成proj3.h,重载复合赋值运算符+=。
要求:
补充编制的内容写在“//**********333**********”与“//**********666**********”之间,不得修改程序的其他部分。
注意:程序最后将结果输出到文件out.dat中。输出函数writeToFih已经编译为obj文件,并且在本程序中调用。
//proj3.h
#include
#include
usingnamespacestd;
classMiniString
{public:
friendostream&operator<<(ostream&output,constMiniString&s)
//重栽流插入运算符
{output<}
friendistream&operator>>(istream&input,MiniString&s)
//重载流提取运算符
{chartemp[i00];//用于输入的临时数组
temp[0]=’\0’;
input>>setw(100)>>temp;
intinLen=strlenktemp);//输入字符串长度
if(inLen!=0)
{
s.length=inLen;//赋长度
if(s.sPtr!=0)delete[]s.sPtr;
//避免内存泄漏
s.sPtr=newchar[s.length+1];
strcpy(s.sPtr,temp);
//如果s不是空指针,则复制内容
}
elses.sPtr[0]=’\0’;
//如果s是空指针,则为空字符串
returninput;
}
MiniString(constchar*S="":length((s!=0)?strlen(S):0)(setString(S);}
~MiniString()fdelete[]sPtr;)//析构函数
//*************333***********
//+=运算符重载
//*************666***********
private:
intlength;//字符串长度
char*sPtr;//指向字符串起始位置
voidsetString(constchar*string2
}//辅助函数
{
sPtr=newchar[length+1];
//分配内存
if(string2!=0)
strcpy(sPtr,string2);
//如果string2不是空指针,则复制内容
elsesPtr[0]=’\0’;
//如果string2是空指针,则为空字符串
  }
};
//proj3.cpp
#include
#include
usingnamespacestd;
#include"proj3.h"
intmain()
{
MiniStringstrl("World"),str2("Hello");
voidwriteToFile(char*);
str2+=strl;//使用重载的+=运算符
cout<writeToFile("");
return0;
}

选项

答案MiniString& operator+=(const MiniString& s) { char *pt = new char [length+1]; strcpy(pt, sPtr); int blength = length; length += s.length; delete []sPtr; sPtr = new char[length+1]; strcpy(sPtr,pt); delete []pt; for (int i = 0; i < length; ++i) sPtr[blength+i] = s.sPtr[i]; return *this; }

解析 主要考查考生对运算符重载的掌握,因为有动态数组,所以要使用new语句来重新分配空间。
转载请注明原文地址:https://kaotiyun.com/show/oBBD777K
0

最新回复(0)