c/c++语言_自定义strcpy函数以及字符串类string的实现

//编写strcpy函数
char * strcpy(char *strDest, const char *strSorce)
{
    assert((NULL!=strDest) && (NULL!=strSorce));
    char *address = strDest;
    while((*strDest++ = *strSorce++) != '\0')
    NULL;
    return address;
}
//编写string类的基本

class myString
{
    public:
    myString(char *str = NULL);
    myString(const myString &other);
    myString & operator =(const myString &other);
    ~myString(void);
    private:
    char *m_str;
};


myString::~myString(void)
{
    delete [] m_str;
}

myString::myString(char *str)
{
    if(NULL == str)
    {
        m_str = new char[1];
        *m_str = '\0';
    }
    else
    {
        int length = strlen(str);
        m_str = new char[length + 1];
        strcpy(m_str, str);
    }
}
myString::myString(const myString &other)
{
    int length = strlen(other.m_str);
    m_str = new char[length + 1];
    strcpy(m_str,other.m_str);
}

myString & myString::operator =(const myString &other)
{
    if(this == &other)
    {
        return *this;
    }
    else
    {
        delete [] m_str;
        int length = strlen(other.m_str);
        m_str = new char[length + 1];
        strcpy(m_str, other.m_str);
        return *this;
    }
}
发布了142 篇原创文章 · 获赞 11 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/weixin_38293453/article/details/104363555