一个string类的简单实现

实现一个string类的简单实现


class CStr      
{
public:
    CStr();
    ~CStr();
    CStr(const char* str);
    CStr(const CStr& cstr);

    CStr& operator=(const CStr& cstr); //重载=运算符
    CStr& operator+=(const CStr& cstr); //重载+=运算符

    CStr& operator=(const char* str); //重载=运算符
    CStr& operator+=(const char* str); //重载+=运算符
    
    const CStr operator+(const CStr& cstr); //重载+运算符
    const CStr operator+(const char* str); //重载+运算符

    operator const char*(); //括号运算符重载

    //友元函数
    friend std::ostream& operator<<(std::ostream &out, const CStr &cstr);

private:
    char* m_str;
};

CStr::CStr()
{
    m_str = NULL;
}

CStr::~CStr()
{
    if (m_str)
    {
        free(m_str);
    }

    m_str = NULL;
}

CStr::CStr(const char* str)
{
    m_str = strdup(str);
}

CStr::CStr(const CStr& cstr)
{
    m_str = strdup(cstr.m_str);
}

CStr& CStr::operator=(const CStr& cstr)
{
    return (*this = cstr.m_str);
}

CStr& CStr::operator+=(const CStr& cstr)
{
    return (*this += cstr.m_str);
}

CStr& CStr::operator=(const char* str)
{
    if (m_str)
    {
        free(m_str);
        m_str = NULL;
    }

    m_str = strdup(str);
    return *this;   
}

CStr& CStr::operator+=(const char* str)
{
    return *this = *this + str;   
}

const CStr CStr::operator+(const CStr& cstr)
{
    int nlen = strlen(m_str);
    nlen += strlen(cstr.m_str);
    CStr str;
    str.m_str = (char *)malloc(nlen + 1);
    strcpy(str.m_str, m_str);
    strcat(str.m_str, cstr.m_str);
    return str;
}

const CStr CStr::operator+(const char* pstr)
{
    int nlen = strlen(m_str);
    nlen += strlen(pstr);
    CStr str;
    str.m_str = (char *)malloc(nlen + 1);
    strcpy(str.m_str, m_str);
    strcat(str.m_str, pstr);
    return str;
}

CStr::operator const char*()
{
   return m_str;
}

std::ostream& operator<<(std::ostream &out, const CStr &cstr)
{
    out << cstr.m_str;
    return out;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值