自己实现的标准C++ string 类

来源:互联网 发布:搞笑淘宝买家秀图对比 编辑:程序博客网 时间:2024/05/18 18:00
 自己实现的 string 类。
  1. #include<iostream>
  2. using namespace std;
  3. class string
  4. {
  5.     friend ostream &operator<<(ostream &, string &) ;
  6. public:
  7.     string(const char *str = NULL);
  8.     string(const string &from);
  9.     string &operator=(const string &other);
  10.     string operator+(const string &rhs) const;
  11.     bool operator==(const string &rhs);
  12.     char &operator[](unsigned int n); 
  13.     size_t size(){return strlen(m_data);}
  14.     ~string(){delete m_data;};
  15. private:
  16.     char *m_data;   
  17. };
  18. inline string::string(const char *str)
  19. {
  20.     if(!str){
  21.         m_data = 0; 
  22.     }
  23.     else{
  24.         m_data = new char[strlen(str) + 1];
  25.         strcpy(m_data, str);    
  26.     }
  27. }
  28. inline string::string(const string &from)
  29. {
  30.     if(!from.m_data){
  31.         m_data = 0; 
  32.     }   
  33.     else{
  34.         m_data = new char[strlen(from.m_data) + 1];
  35.         strcpy(m_data, from.m_data);    
  36.     }
  37. }
  38. inline string &operator=(const string &other)
  39. {
  40.     if(this != &other)
  41.     {
  42.         delete m_data[];
  43.         if(!other.m_data){
  44.             m_data = 0; 
  45.         }   
  46.         else{
  47.             m_data = new char[strlen(other.m_data) + 1];
  48.             strcpy(m_data, other.m_data);   
  49.         }
  50.     }
  51.     return *this;
  52. }
  53. inline string string::operator+(const string &rhs) const
  54. {
  55.     string newString;
  56.     if(!other.m_data){
  57.         newString = *this;
  58.     }   
  59.     else if(!m_data){
  60.         newString = rhs;    
  61.     }
  62.     else{
  63.         newString = new char[strlen(m_data)+ strlen(rhs.m_data) + 1];
  64.         strcpy(newString.m_data, m_data);
  65.         strcat(newString.m_data, rhs.m_data);   
  66.     }
  67.     return newString;
  68. }
  69. inline bool string::operator==(const string &rhs)
  70. {
  71.     if(strlen(m_data) != strlen(rhs.m_data)){
  72.         return false;   
  73.     }
  74.     else{   
  75.         return strcmp(m_data, rhs.m_data)?false:true;
  76.     }   
  77. }
  78. inline char &string::operator[](unsigned int n)
  79. {
  80.     if(n >= 0 && n <= strlen(m_data)){
  81.         return m_data[n];   
  82.     }   
  83. }
  84. ostream &operator<<(ostream &os, string &str)
  85. {
  86.     os<<str.m_data;
  87.     return os;
  88. }

有不完善的地方,将继续补充。

原创粉丝点击