C + + reaches string classification

Source: Internet
Author: User

This is a very classic face question, able to test students for a short time C + + mage is a synthesis, the answer should contain most of C + + knowledge class, guarantee string character class can complete the value, copy, variables and other functions of the definition.


#include <iostream>using namespace Std;class string{public:string (const char *str=null);       String (const string &other);       ~string (void); String &operator = (const string &other);p Rivate:char *m_data;};    string::string (const char *str) {cout<< "constructor was called" <<endl; if (str==null)//Avoid the presence of wild pointers, such as String B; Suppose there is no such sentence.        There will be wild//pointer {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 (void) {delete m_data; cout<< "destructor was called" &LT;&LT;ENDL;} string::string (const String &other) {cout<< "assignment constructor was called" <<endl; int Length=strlen (other.m_data); m_ Data=new char[length+1]; strcpy (m_data,other.m_data);}      String &string::operator= (const string &other) {cout<< "assignment function was called" <<endl;      if (this==&other)//Copy yourself without copying the return *this; Delete m_data;//the pointer variable in the Assigned objectTo the previous memory space, avoid//memory leak int Length=strlen (other.m_data);//Calculate length m_data=new char[length+1];//application Space strcpy (m_data,other.m_data);//Copy return *this;} void Main () {string b;//call constructor string A ("Hello");//Call Constructor string C ("World");//Call constructor string d=a;//call assignment constructor function. Since the d=c;//overloaded assignment function call was initialized with a during the creation of the D object,}

Copyright notice: This article Bo Master original articles, blogs, without consent may not be reproduced.

C + + reaches string classification

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.