自定义的字符串类
2015-11-03 11:08
459 查看
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';的操作
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- Lua中调用C++函数示例
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C++联合体转换成C#结构的实现方法
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结
- 使用Lua来扩展C++程序的方法
- C++中调用Lua函数实例
- Lua和C++的通信流程代码实例
- C与C++之间相互调用实例方法讲解
- 解析C++中派生的概念以及派生类成员的访问属性
- C++ Custom Control控件向父窗体发送对应的消息