自定义的字符串类

来源:互联网 发布:软件培训怎么样 编辑:程序博客网 时间:2024/05/22 12:44
class CTextClass{    public:        CTextClass(char *pText)    {        Copy(pText);    }        ~CTextClass()    {        Delete();    }        CTextClass(const CTextClass &text)    {        Copy(text.m_pText);    }        CTextClass& operator= (const CTextClass &text)    {        if (&text == this)            return *this;                // 需要先删除        Delete();        Copy(text.m_pText);                return *this;    }        char& operator[] (const int index)    {        if (index >= m_length)            throw std::bad_exception();                return m_pText[index];    }        // 需要返回常量否则仍旧可以修改成员变量的值    const char& operator[] (const int index) const    {        if (index >= m_length)            throw std::bad_exception();                return m_pText[index];    }        friend std::ostream& operator << (std::ostream &os, const CTextClass &text);    private:        void Copy(char *pText)    {        m_length = strlen(pText) + 1;        if (m_length == 0)        {            m_length = 1;            m_pText = new char[m_length];        }        else        {            m_pText = new char[m_length + 1];            strcpy(m_pText, pText);        }                m_pText[m_length - 1] = 0;    }        void Delete()    {        if (m_pText)            delete m_pText;                m_pText = nullptr;        m_length = 0;    }        // 禁止使用C++11的转移语法    CTextClass(CTextClass &&text);    CTextClass& operator= (CTextClass &&text);    private:        char* m_pText;    size_t m_length;    };// 输出test中的内容std::ostream& operator << (std::ostream &os, const CTextClass &text){    return os << text.m_pText << std::endl;}


需要注意:

1. operator= 重载需要注意判断是否是自己赋值给自己,如果不是自己赋值给自己,需要先将之前的删除掉

2. 常成员函数operator[] 返回值需要是常引用,如果不是就仍旧可以通过 text[0] = 'a'; 来修改成员变量的值

3. 非常成员函数operator[] 返回值需要是引用,需要可以进行赋值操作,否则编译器会报错,需要可以执行text[0] = 'a';的操作



0 0
原创粉丝点击