We may often encounter this problem during the interview, so we need to review the problem.
Because of the time requirement, we can not write std::string that function, we need to be able to achieve the overall function.
#include <iostream> #include <cstdlib> using namespace std; Class String {friend ostream& operator<< (ostream& os,string& str); public:string (const char *
Str= ""): _str (new Char[strlen (str) +1]) {strcpy (_str, str);
} String (const string &str): _str (New Char[strlen (STR._STR) +1]) {strcpy (_str, STR._STR);
} ~string () {if (_str!= NULL) {
Delete[] _STR;
_str = NULL;
} The string& operator= (const string& str)//assignment operator needs to be modified before the reference can be made.
{if (this!= &str) {delete[] _str;
_str = new Char[strlen (STR._STR) + 1];
strcpy (_str, STR._STR);
return *this;
////more modern, the assignment operator Overloads//string& operator= (String str)//{//Std::swap (_STR, STR._STR);
In this exchange, after the exchange, and then use the function of the Copy mechanism, to destroy the given one.
return *this;
} Private:char *_str;
};
ostream& operator<< (ostream& os, string& str) {OS << str._str;
return OS;
int main () {String S1 ("123455");
String S2;
s2 = S1;
String S3 (S1);
cout << s1 << S2 << Endl;
cout << S3 << Endl;
System ("pause");
return 0; }