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

Source: Internet
Author: User

The differences between the copy constructor and the value assignment function are as follows:Code, Think about the difference between the two.

The copy constructor is called when an object is defined, as shown in figure

Class string {//...}; string a = B; // B is a string type object or string A (B );

The value assignment function is called when a class instance is assigned to another instance, for example

String A; A = B;

The prototype of the constructor, destructor, and assignment function of the string type is as follows:

Class string {public: string (const char * STR = NULL); // constructor string (const string & other); // copy constructor ~ String (void); // destructor string & operator = (const string & other); // value assignment function PRIVATE: char * m_data; // save string }; // constructorstring: string (const char * Str) {If (STR = NULL) {m_data = new char [1]; m_data [0] = '\ 0 ';} else {int Len = strlen (STR); m_data = new char [Len + 1]; Assert (m_data! = NULL); strcpy (m_data, STR) ;}// copy constructor: Use string: string (const string & Other) when defining a Type Variable) {int length = strlen (Other. m_data); m_data = new char [Length + 1]; Assert (m_data! = NULL); strcpy (m_data, other. m_data);} // destructorstring ::~ String (void) {Delete [] m_data;} // value assignment function: used to assign a class instance to another class instance string & string :: operator = (const string & Other) {If (this = & Other) {return * This;} Delete [] m_data; int length = strlen (Other. m_data); m_data = new char [Length + 1]; Assert (m_data! = NULL); strcpy (m_data, other. m_data); return * This ;}

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: 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.