"C + + FAQ"-Write a string implementation

Source: Internet
Author: User

The implementation of a string class must be sketched out quickly.

1 classString2 {3      Public:4String (Const Char*STR = NULL);//Common Constructors5String (ConstString &other);//copy Constructor6~ String (void);// Destructors7String &operator=(ConstString &other);//Assignment Function8     Private:9     Char*m_data;//used to save stringsTen }; One  A //Common Constructors -String::string (Const Char*str) - { the     if(str==NULL) -     { -M_data =New Char[1];//automatic application of an empty string to the closing flag '//Add points: null judgment on M_data -*m_data =' /'; +}Else{ -         intLength =strlen (str); +M_data =New Char[length+1];//Better if you can add a NULL judgment A strcpy (m_data, str); at     } - } -  - //destructor for string -String::~string (void) - { inDelete[] m_data;//or delete m_data; - } to  + //copy Constructor -String::string (ConstString &other)//input parameter is const type the { *     intLength =strlen (other.m_data); $M_data =New Char[length+1];//null judgment for M_dataPanax Notoginseng strcpy (m_data, other.m_data); - } the  +String & string::operator=(ConstString &other)//input parameter is const A type the { +     if( This! = &other)//Check self-assigned value - { $ String strtemp (str); $     Char* Ptemp =Strtemp.m_pdata; -Strtemp.m_pdata =m_pdata; -M_pdata =ptemp; the } -     return* This;//returns a reference to this objectWuyi}
View Code
1 //assignment function, poor practice2String & string::operator=(ConstString &other)//input parameter is const3 type4 {5     if( This= = &other)//Check self-assigned value6     return* This;7Delete[] m_data;//freeing up legacy memory resources8     intLength =strlen (other.m_data);9M_data =New Char[length+1];//null judgment for M_dataTen strcpy (m_data, other.m_data); One     return* This;//returns a reference to this object A}
View Code

"C + + FAQ"-Write a string implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.