String::String(const char *s)
{
int len;
char s_temp;
length = strlen(s);
pBuf = new char[length+1]; //pBuf是String类中的 char* 变量
while(*s != '\0')
{
*pBuf++ = *s++;
}
*pBuf = '\0';
cout << "initializing pBuff: " << pBuf << endl;
cout << "length: " << length << endl;
}
程序运行之后,pBuf没有打印出内容。反复查找原因,终于发现了问题。
原来,*pBuf++ = *s++;
的时候,pBuf的位置已经改变了,再通过cout打印出来的时候,pBuf的位置已经在 pBuf[length+1]处,所以没有内容。
解决办法,先定义一个 char *p, 将pBuf保存起来,再做复制操作。