编写String的构造函数、析构函数、拷贝构造函数、赋值函数
2016-04-19 15:04
441 查看
函数原型
class String { public: String(const char* str = ""); ~String(); String(const String& other); String&::operator=(const String& other); };
String的普通构造函数
String::String(const char* str) { if (str == NULL) { m_data = new char[1]; m_data = '\0'; } else { int length = strlen(str); m_data = new char[length + 1]; strcpy(m_data,str); } }
String的析构函数
String::~String() { delete []m_data; }
String的拷贝构造函数
String::String(const String& other) { int length = strlen(other.m_data); m_data = new char[length + 1]; strcpy(m_data, other.m_data); } // 赋值函数 String&::operator=(const String& other) { // 1.判断是否是自赋值 if (this != other) { // 2.分配新的内存 char* temp = new char[strlen(other.m_data) + 1]; strcpy(temp,other.m_data); // 3.释放旧资源,并指向新的资源 delete []m_data; m_data = temp; } // 4.返回对象 return *this; }
相关文章推荐
- ThinkPHP 3.1.2 模板中的变量
- iOS_导入libxml2.2框架后,找不到<libxml/tree.h>的解决办法
- [HSON : HC Script Object Notation] Finish Build 1 On GitHub
- php编码解码json对象
- APK瘦身实践
- using的作用
- ThinkPHP 3.1.2 模板中的变量
- ThinkPHP 3.1.2 模板中的变量
- 如何选择适合自己的CMS建站系统
- VirtualBox下Ubuntu利用桥接方式上网
- 初学遗传算法解决tsp问题(C++)
- jQuery的选择器
- oom解决方式
- 【01背包/母函数】HDU2079选课时间(题目已修改,注意读题)【用背包求解方案数】
- modsecurity系列二:主文件配置
- 【client】与【offset】
- 采用MogoDB生成ID的策略
- Java对英文句子进行倒序排序
- VC回车键的使用 Edit内回车
- SpringMVC中使用Interceptor拦截器