Identification of copy constructor and value assignment function

Source: Internet
Author: User

(1) test yourself. can you differentiate it?

String A ("zhangbufeng ");
String B ("cuixiaoyuan ");
String C (a); // when creating an object, use the copy constructor.
C = B; // C has been initialized and the value assignment function is called. The last time I wrote more strings, the definition was redefined.

 

(2) code verification

 

 

# Include <iostream>
# Include <string>
Using namespace STD;

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_string; // Private member, saving the string
};
String ::~ String (void)
{
Cout <"destructing" <Endl;
Delete [] m_string;

}

String: string (const char * Str)
{
Cout <"construcing" <Endl;
If (STR = NULL)
{
M_string = new char [1];
* M_string = '/0 ';
}
Else
{
Int length = strlen (STR );
M_string = new char [Length + 1];
Strcpy (m_string, STR );
}
}
String: string (const string & other)
{
Cout <"constructing copy" <Endl;
Int length = strlen (other. m_string );
M_string = new char [Length + 1];
Strcpy (m_string, other. m_string );
}
String & string: Operator = (const string & other)
{
Cout <"operate = function" <Endl;

// Check auto-assigned values
If (this = & other)
Return * this;
 
// Release the original memory resource
Delete [] m_string;

// Allocate new memory resources and copy the content
Int length = strlen (other. m_string );
M_string = new char [Length + 1];
Strcpy (m_string, other. m_string );

// Return the reference of this object
Return * this;
}
Void main ()
{
String A ("zhangbufeng ");
String B ("cuixiaoyuan ");
String C ();
C = B;
String d =;
}

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.