Interview question 6: Write string-like constructor, copy constructor, destructor, and assignment function

Source: Internet
Author: User

The prototype of the known class string is:

Class string

{

Public:

String (const char * STR = NULL); // common Constructor

String (const string & other); // copy the constructor

~ String (void); // destructor

String & operator = (const string & other); // value assignment function

PRIVATE:

Char * m_data; // used to save strings

};

Write the above four functions of string

 

/* Destructor */

String ::~ String (void)

{

Delete [] m_data; // because m_data is an internal data type, you can also write it as delete m_data;

}

 

/* Common constructor */

String: string (const char * Str)

{

If (STR = NULL)

{

M_data = new char [1];

* M_data = '\ 0 ';

}

Else

{

Int Len = strlen (STR );

M_data = new char [Len + 1];

Strcpy (m_data, STR );

}

}

/* Copy the constructor */

String: string (const string & other)

{

Int Len = strlen (other. m_data );

M_data = new char [Len + 1]; // m_data is directed only to the applied space. It is only a pointer before it is applied, not to the specified memory space.

If (m_data! = NULL)

Strcpy (m_data, other. m_data );

}

/* Value assignment function */

String & string: Operator = (const string & other)

{

If (this = & other)

Return * this;

Delete [] m_data; // release the original memory resource

Int Len = strlen (other. m_data );

M_data = new char [Len + 1]; // allocate new memory resources

If (m_data! = NULL)

Strcpy (m_data, other. m_data );

Return * This; // return the reference of this object

}

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.