String的构造函数、析构函数和赋值函数
编写类String的构造函数、析构函数和赋值函数
已知类String的原型为:
class String
{
public:
String(const char *str = NULL); // 普通构造函数
String(const String &other); // 拷贝构造函数
~ String(void); // 析构函数
String & operate =(const String &other); // 赋值函数
private:
char *m_data; // 用于保存字符串
};
请编写String的上述4个函数。
标准答案:
// String的析构函数
String::~String(void)
{
delete [] m_data; // 由于m_data是基本数据类型的数组,也可以写成 delete m_data;
}
// String的普通构造函数
String::String(const char *str)
{
if(str==NULL)
{
m_data = new char[1]; // 若能加 NULL 判断则更好
*m_data = ‘\0’;
}
else
{
int length = strlen(str);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, str);
}
}
// 拷贝构造函数
String::String(const String &other)
{
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data);
}
// 赋值函数
String & String::operate =(const String &other)
{
// (1) 检查自赋值
if(this == &other)
return *this;
// (2) 释放原有的内存资源
delete [] m_data;
// (3)分配新的内存资源,并复制内容
int length = strlen(other.m_data);
m_data = new char[length+1]; // 若能加 NULL 判断则更好
strcpy(m_data, other.m_data);
// (4)返回本对象的引用
return *this;
}
最新文章
- SpringMVC注入Spring的bean
- Mono-D在MacOS上的设置
- 在asp.net mvc模式中使用PartialView返回部分HTML
- BFC and Haslayout
- UITableView表视图以及重建机制
- (转载)UITableView的详细讲解
- gitlab的安装以及汉化
- 【转】 树莓派学习笔记——I2C设备载入和速率设置
- LeeCode-Sort Colors
- js获得url内的参数
- 开源 免费 java CMS - FreeCMS1.9 职位管理
- MongoDB学习之--安全和认证
- Firebase 相关
- [转]如何使用PHP实现javascript的escape和unescape函数
- SSH深度历险(三) EJB Session Bean有状态和无状态的区别与联系
- canvas-a13prototype.html
- LOJ 3089: 洛谷 P5319: 「BJOI2019」奥术神杖
- 洛谷P4358密钥破解 [CQOI2016] 数论
- Ubuntu17.04下安装vmware虚拟机
- ubuntu卸载软件命令,apt-get remove
热门文章
- ZOJ3784 String of Infinity 高大上的AC自动机 数据原来这么水啊!不算输入输出只有5-7行
- Object的增。删。查。改。遍历
- char* 和 wchar_t* 如何互相转换
- Android RadioGroup/RadioButton
- 用JavaScript获取地址栏参数的方法
- 函数 setjmp, longjmp, sigsetjmp, siglongjmp
- 【转】IOS开发小技巧
- php面向对象编程学习之高级特性
- AndroidAutoLayout 屏幕适配
- 使用border-image实现类似iOS7的1px底边