C + + String class (construction, copy construction, assignment operator overloading, and destructor)

Source: Internet
Author: User

Class String

{

Public

Common constructors

String (const char *STR = NULL)

{

if (str = = NULL)

{

m_data = new Char[1];

*m_data = ' + ';

}

Else

{

m_data = new Char[strlen (str) + 1];

strcpy (m_data, str);

}

}

Copy constructor

String (const string &s)

{

m_data = new Char[strlen (s) + 1];

strcpy (M_data, s.m_data);


}

Assignment operator overloading

String & operator= (const string &s)

{

if (this = = &s)

{

return *this;

}

delete [] m_data;

m_data = new Char[strlen (s.m_data) + 1];

strcpy (M_data, s.m_data);

return *this;

}

Destructors

~string ()

{

if (m_data! = NULL)

{

delete [] m_data;

m_data = NULL;

}

}

Private

Char *m_data;

}

For assignment operator overloading there are three points to note:

The return value should be a reference to increase efficiency, or the return value will generate a temporary copy.

Second, the parameters should be applied, for a reason.

The parameter is set to the const type, preventing parameters from being modified inside the function.


C + + String class (construction, copy construction, assignment operator overloading, and destructor)

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.