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" <<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