Four default member functions of the String class

Source: Internet
Author: User

Four default member functions of the String class

# Include
  
   
# Include
   
    
# Pragma warning (disable: 4996) using namespace std; class String {public: String (char * p): _ ptr (new char [strlen (p) + 1]) {if (_ ptr! = 0) {strcpy (_ ptr, p) ;}} void swap (String & s) {char * tmp = s. _ ptr; s. _ ptr = _ ptr; _ ptr = tmp;} // optimized String (const String & s): _ ptr (NULL) // _ ptr must be set to NULL, otherwise, an error occurred while releasing a random value {String tmp (s. _ ptr); swap (tmp);}/* String & operator = (const String & s) {if (this! = & S) {String tmp (s. _ ptr); swap (tmp);} return * this;} * // optimal String & operator = (String s) {swap (s); return * this ;} // original version/* String (const String & s) {_ ptr = new char [strlen (s. _ ptr) + 1]; if (_ ptr! = 0) {strcpy (_ ptr, s. _ ptr) ;}} String & operator = (const String & s) {if (this! = & S) {delete _ ptr; _ ptr = new char [strlen (s. _ ptr) + 1]; if (_ ptr! = 0) {strcpy (_ ptr, s. _ ptr) ;}} return * this ;}*/~ String () {if (_ ptr) {delete [] _ ptr ;}} void Display () {cout <_ ptr <endl;} private: char * _ ptr;}; int main () {String s1 (yangrujing), s2 (yangfeipan); String s3 (s1); s3.Display (); s1 = s2; s1.Display (); getchar (); return 0 ;}
   
  

 

Related Article

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.