Constructor, destructor, and value assignment functions of the string type

Source: Internet
Author: User

The prototype of the known class string is:

Class string <br/>{< br/> Public: <br/> string (const char * STR = NULL ); // normal constructor <br/> string (const string & other); // copy constructor <br/> ~ String (void); // destructor <br/> string & operate = (const string & other); // value assignment function <br/> PRIVATE: <br/> char * m_data; // used to save the string <br/> };

Write the above four functions of string

// String destructor <br/> string ::~ String (void) // 3 points <br/>{< br/> Delete [] m_data; <br/> // because m_data is an internal data type, you can also write it as delete m_data; <br/>}

// String constructor <br/> string: string (const char * Str) // 6 points <br/>{< br/> If (STR = NULL) <br/>{< br/> m_data = new char [1]; // It is better if null can be added <br/> * m_data = '/0 '; <br/>}< br/> else <br/>{< br/> int length = strlen (STR ); <br/> m_data = new char [Length + 1]; // It is better if null can be added <br/> strcpy (m_data, STR ); <br/>}< br/>

// Copy the constructor <br/> string: string (const string & Other) // 3 points <br/>{< br/> int length = strlen (Other. m_data); <br/> m_data = new char [Length + 1]; // It is better if null can be added <br/> strcpy (m_data, other. m_data); <br/>}

// value assignment function <br/> string & string: operate = (const string & other) // 13 points <br/>{< br/> // (1) Check the auto-assigned value // 4 points <br/> If (this = & other) <br/> return * This; <br/> // (2) release the original memory resource // 3 points <br/> Delete [] m_data; <br/> // (3) allocate new memory resources and copy the content. // 3 points <br/> int length = strlen (Other. m_data); <br/> m_data = new char [Length + 1]; // It is better if null can be added <br/> strcpy (m_data, other. m_data); <br/> // (4) returns the reference of this object // 3 points <br/> return * this; <br/>}

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.