编写类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;

}

最新文章

  1. SpringMVC注入Spring的bean
  2. Mono-D在MacOS上的设置
  3. 在asp.net mvc模式中使用PartialView返回部分HTML
  4. BFC and Haslayout
  5. UITableView表视图以及重建机制
  6. (转载)UITableView的详细讲解
  7. gitlab的安装以及汉化
  8. 【转】 树莓派学习笔记——I2C设备载入和速率设置
  9. LeeCode-Sort Colors
  10. js获得url内的参数
  11. 开源 免费 java CMS - FreeCMS1.9 职位管理
  12. MongoDB学习之--安全和认证
  13. Firebase 相关
  14. [转]如何使用PHP实现javascript的escape和unescape函数
  15. SSH深度历险(三) EJB Session Bean有状态和无状态的区别与联系
  16. canvas-a13prototype.html
  17. LOJ 3089: 洛谷 P5319: 「BJOI2019」奥术神杖
  18. 洛谷P4358密钥破解 [CQOI2016] 数论
  19. Ubuntu17.04下安装vmware虚拟机
  20. ubuntu卸载软件命令,apt-get remove

热门文章

  1. ZOJ3784 String of Infinity 高大上的AC自动机 数据原来这么水啊!不算输入输出只有5-7行
  2. Object的增。删。查。改。遍历
  3. char* 和 wchar_t* 如何互相转换
  4. Android RadioGroup/RadioButton
  5. 用JavaScript获取地址栏参数的方法
  6. 函数 setjmp, longjmp, sigsetjmp, siglongjmp
  7. 【转】IOS开发小技巧
  8. php面向对象编程学习之高级特性
  9. AndroidAutoLayout 屏幕适配
  10. 使用border-image实现类似iOS7的1px底边