操作符重载案例之字符串重载

素颜马尾好姑娘i 2022-06-09 12:27 275阅读 0赞

本次案例自定义一个字符串类(Mystring),然后重载该字符串类以后,就可以向使用string类一样使用Mystring类了;

Mystring.h文件:

  1. #ifndef __MYSTRING_H
  2. #define __MYSTRING_H
  3. class Mystring{
  4. friend void print(Mystring & oop);
  5. public:
  6. /*空串 “”*/
  7. Mystring();
  8. Mystring(char *str);
  9. Mystring(Mystring &oop);
  10. ~Mystring();
  11. Mystring& operator=(Mystring &oop);
  12. private:
  13. int str_len;
  14. char *str;
  15. };
  16. void print(Mystring & oop);
  17. #endif

Mystring.cpp文件:

  1. #define _CRT_SECURE_NO_WARNINGS
  2. #include "Mystring.h"
  3. #include <iostream>
  4. #include <string.h>
  5. Mystring::Mystring()
  6. {
  7. str_len = 0;
  8. this->str = new char[this->str_len + 1];
  9. strcpy(this->str, "");
  10. }
  11. Mystring::Mystring(char *str)
  12. {
  13. if (str == NULL)
  14. {
  15. str_len = 0;
  16. this->str = new char[this->str_len + 1];
  17. strcpy(this->str, "");
  18. }
  19. else
  20. {
  21. this->str_len = strlen(str);
  22. this->str = new char[str_len+1];
  23. strcpy(this->str,str);
  24. }
  25. }
  26. /*拷贝构造函数*/
  27. Mystring::Mystring(Mystring & oop)
  28. {
  29. this->str_len = oop.str_len;
  30. this->str = new char[str_len + 1];
  31. strcpy(this->str,oop.str);
  32. }
  33. /*析构函数*/
  34. Mystring::~Mystring()
  35. {
  36. if (this->str != NULL)
  37. {
  38. delete [] this->str;
  39. this->str = NULL;
  40. this->str_len = 0;
  41. std::cout << "析构函数生效" << std::endl;
  42. }
  43. }
  44. /*输出字符串信息*/
  45. void print(Mystring & oop)
  46. {
  47. std::cout << oop.str << std::endl;
  48. }
  49. /*等号操作符重载*/
  50. Mystring & Mystring::operator=(Mystring &oop)
  51. {
  52. this->str_len = oop.str_len;
  53. this->str = new char[str_len + 1];
  54. strcpy(this->str, oop.str);
  55. return *this;
  56. }

main.cpp为测试内容:

  1. #include <iostream>
  2. #include "Mystring.h"
  3. using namespace std;
  4. int main()
  5. {
  6. {
  7. Mystring oop1("baibai");
  8. Mystring oop2("nihao");
  9. Mystring oop3 = oop2;//调用构造函数实现
  10. print(oop3);
  11. oop2 = oop1;//“字符串复制操作,通过等号运算符重载实现”
  12. print(oop2);
  13. }
  14. system("pause");
  15. return 0;
  16. }

发表评论

表情:
评论列表 (有 0 条评论,275人围观)

还没有评论,来说两句吧...

相关阅读

    相关 C++操作符重载

    又看了一遍操作符的东西,感觉之前对操作符的理解还停留在很浅的认知上(仅仅会用哈哈),所以做一下笔记来加深一下印象。 文章目录 一、为什么会有操作符重载

    相关 C++中操作符重载

    一、操作符重载属于什么? 在本文开始阐述之前,首先明确,操作符重载是一个具有特殊名的“ 函数 ”。 既然作为函数,那么,就具有函数的特性,一是形参表,二是返回值。 关键字