Compile string constructor, destructor, and value assignment function

Source: Internet
Author: User

# Include <iostream>

Using namespace STD;

Class string
{
Public:
String (const char * STR = NULL );
String (const string & other );
~ String (void );
String & operator = (const string & other );
Const char * getstring () const;

PRIVATE:
Char * m_data;
};

String ::~ String (void)
{
Delete [] m_data;
}

String: string (const char * Str)
{
If (STR = NULL)
{
M_data = new char [1];
* M_data = '\ 0 ';
}
Else
{
Int length = strlen (STR );
M_data = new char [Length + 1];
Strcpy (m_data, STR );
}
}

String: string (const string & other)
{
Int length = strlen (other. m_data );
M_data = new char [Length + 1];
Strcpy (m_data, other. m_data );
}

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];
Strcpy (m_data, other. m_data );

Return * this;
}

Const char * string: getstring () const
{
Return m_data;
}

Int main ()
{
String STR ("hello ");
String str1 ("Meng ");
String str2 (str1 );
String str3 ("Jun .");
String str4 (str3 );
String str5 = str4;

Cout <Str. getstring () <str2.getstring () <str5.getstring () <Endl;

Return 0;
}

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.