c++实现mystring

来源:互联网 发布:jquery.min.js下载1.9 编辑:程序博客网 时间:2024/05/16 05:44


以下仅为个人理解:


#include "mytstring.h"
#include <iostream>
#include <string.h>
mytstring::mytstring():s(NULL)
{
}
mytstring::mytstring(const char *s)
{
    int len = strlen(s);
    this->s = new char[len+1];
    strcpy(this-s,s);
    this->s[len] = 0 ;
}


问1:为什么要加1

答:

strlen返回的都是字符数目,相加到一起后就是总字符数。不过,字符串在结尾处有一个 '\0' 用于标记末尾(即使是"Mary and Linda "这样的静态字符串也会有一个隐含的'\0'在最后),所以需要一个位置(strcat,strcpy都会自动加上这个结束符,所以你不知道)。
问2:为什么要len=0

答:

如果len=6,那么,new char[6+1],之后,这个数组可以装7个char,但是第七个是装'\0'的。我们访问数组时,访问第一个元素,s[0] ,访问第二个元素, s[1] ,所以访问第七个元素时,s[6]。一句话,其实,数组下标,是从0开始的。如图:

    




0 0