Implement a compact version of class String#include <iostream> #include <string.h>using namespace Std;class string{public: String () {_str = new char[1];_str[0] = ' + ';} String (const char *str) {_str = new Char[strlen (str) + 1];strcpy (_str, str);} String (const string &s) {_str = new Char[strlen (S._STR) + 1];strcpy (_str, s._str);} string& operator= (const String &s) {/*if (This! = &s) //Common method defective {delete[] _str;_str = new Char[strlen (s._ STR) + 1];strcpy (_str, s._str);} Return *this;*/if (&s! = this) //exception-Safe Divine Assignment {String tmp (S._STR); Swap (_str, tmp._str);} return *this;} ~string () {if (_STR) delete[] _str;} void print () {cout << _str << Endl;} Private:char * _STR;}; int main () {String S1; String S2 ("abcdef"); String S3 (S2); String S4 = S3;S1 = S2;s1.print (); S2.print (); S3.print (); S4.print (); return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
"C + +" implements a concise version of Class String