MyString.h


  
  1. #ifndef _MY_STRING_H_ 
  2. #define _MY_STRING_H_ 
  3. class MyString 
  4. public: 
  5.  
  6.     // explicit 修饰后的构造函数,不能进行隐示转换 
  7.     explicit  MyString(const char* str = ""); 
  8.  
  9.     //深拷贝 
  10.  
  11.     MyString(const MyString& other); 
  12.  
  13.     // =号运算符重载 
  14.     MyString& operator = (const MyString& other); 
  15.  
  16.     MyString& operator = (const  char* str); 
  17.  
  18.     // ! 非运算符重载 
  19.     bool operator !()const; 
  20.     ~MyString(); 
  21.  
  22.     void display(); 
  23.  
  24. private : 
  25.     char* AllocAndCpy(const char* str); 
  26.     char* str_; 
  27. }; 
  28.  
  29. #endif //_MY_STRING_H_ 
MyString.cpp

  
  1. #pragma warning(disable:4996)//屏蔽错误提示 
  2. #include "MyString.h" 
  3. #include <iostream> 
  4. #include <string.h> 
  5.  
  6. using namespace std; 
  7.  
  8. MyString::MyString(const char* str) 
  9.  
  10.     cout<<"MyString("<<str<<")"<<endl
  11.     str_ =AllocAndCpy(str); 
  12.  
  13.  
  14. MyString::~MyString() 
  15.  
  16.     //new出来的就要释放掉 
  17.  
  18.     delete[] str_; 
  19.  
  20.  
  21.  MyString::MyString(const MyString& other){ 
  22.  
  23.      cout<<"MyString(const MyString& other)("<<other.str_<<")"<<endl
  24.     str_ =AllocAndCpy(other.str_); 
  25.  
  26.      
  27.  
  28. char* MyString::AllocAndCpy(const char* str){ 
  29.  
  30.  
  31.     //计算长度 
  32.     int len =strlen(str); 
  33.     //分配空间 
  34.     char* newnewchar = new char[len]; 
  35.     memset(newchar,0,len); 
  36.     //进行copy 
  37.     strcpy(newchar,str); 
  38.  
  39.     return newchar; 
  40.  
  41.  
  42. void MyString::display(){ 
  43.  
  44.     cout<<str_<<endl
  45.     } 
  46.  
  47. MyString& MyString::operator=(const MyString& other){ 
  48.  
  49.  
  50.     cout<< "= operation"<<endl
  51.     if(this == &other){ 
  52.         return *this; 
  53.     } 
  54.     delete [] str_; 
  55.  
  56.     str_AllocAndCpy(other.str_); 
  57.  
  58.     return *this; 
  59.  
  60.  
  61.  
  62. MyString&  MyString::operator = (const  char* str){ 
  63.  
  64.  
  65.   str_AllocAndCpy(str); 
  66.  
  67.     return *this; 
  68.  
  69.  
  70. bool MyString::operator !()const{ 
  71.  
  72.  
  73.     return strlen(str_)!=0;