Implementation of class string constructors, copy constructors, destructors, and assignment functions

Source: Internet
Author: User
Class String class String {public:string (const char *STR = NULL);//constructor string (const string &other);//Copy Constructor ~s Tring (void); destructor string &operator = (const string &other); The assignment function Private:char *m_data;

Used to save the string};
		Constructor string::string (const char *str) {if (str = NULL)//judgment is null {m_data = new char[1];
	*m_data = ' n ';
		else {int len = strlen (str);
		m_data = new Char[len+1];
	strcpy (m_data, str); }//Copy constructor (must be used when constructing an object)//When the object is constructed, the object does not occupy memory at this time, without releasing string::string (const String &other) {int len = strlen (other.m_da
	TA);
	m_data = new Char[len+1];
strcpy (M_data, other.m_data); }//Assignment function (memory space occupied)//1. Before assigning a value, determine whether to assign value//2. Before assigning, the memory space is ready: The object already has a certain amount of memory before the assignment, but the size of the assigned object is not necessarily the same as the size of the object occupied//memory; Release the memory that the object already occupies.
The new memory is then allocated. String & string::operator = (const string &other) {if (&other = this)//to determine if self assignment {return this;} de lete []m_data;
	Frees object occupied memory int len = strlen (other.m_data); m_data = new Char[len+1];
	
Reallocate Memory strcpy (m_data, other.m_data);	return this;
 }//destructor string::~string () {delete []m_data;}

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.