c ++ variable length of the String class

#include <the iostream>  
#include <CString>
 the using  namespace STD; 

class String 
{ 
Private :
     char * STR;
 public : 
    String (): STR (NULL) {}; 
    const  char * getStr () const // here that to set up It is a constant member function, str points to prevent the content is modified. 
    {
         Return STR; 
    } 
    String & operator = ( const String &); // Assignment operator to achieve deep copy 
    String ( const String &);     // copy constructor implemented deep copy

    String & operator = ( const  char * );
     ~ String (); 

}; 

String & String :: operator = ( const String & S) 
{ 
    IF (s.str == STR) // prevent their own replication occurs inadvertently the bugs 
        return * the this ;
     IF (STR) 
    { 
        Delete [] STR; 
        STR = new new  char [strlen (s.str) + . 1 ]; 
        strcpy (STR, s.str); 
    } 
    the else 
        STR =NULL;
    return *this;
}
String::String(const String & s)
{
    str=new char(strlen(s.str)+1);
    strcpy(str,s.str);
}

String & String::operator=(const char * s)
{
    if(str)
        delete []str;
    if(s)
    {
        str=new char[strlen(s)+1];
        strcpy(str,s);
    }
    else
    {
        str=NULL;
    }
    return *this;
}
String::~String()
{
    if(str)
        delete [] str;
}

int main()
{
    
        String s,s1;
        s="xxx";
        cout<<s.getStr()<<endl;
        s="ssss";
        cout<<s.getStr()<<endl;

        s=s;
        s1="ddddd";
        s=s1;

    


    return 0;
}

 

Guess you like

Origin www.cnblogs.com/cq0143/p/11299360.html