#include<iostream>
using namespace std;
class String
{
public:
String(char * str="") //不能strlen(NULL)
:_str(new char [strlen(str ) + 1])
{
strcpy(_str, str);
}
String(const String &s)
:_str(NULL )
{
String tmp(s ._str);
swap(_str,tmp._str);
}
//String& operator=(const String& s)
//{
// if (this != &s)
// {
// String tmp(s._str);
// swap(_str, tmp._str);
// }
// return *this;
//}
String& operator=(String s) //优化 (s不能加引用,否则会改变实参的值)(这里的s是实参的一份拷贝)
{
swap(_str, s._str);
return *this ;
}
char* CStr()
{
return _str;
}
~String()
{
delete[] _str;
}
private:
char* _str;
};
void Test()
{
String s1("aaaaa" );
cout << s1.CStr() << endl;
String s2(s1);
cout << s2.CStr() << endl;
String s3 = s1;
s3= s2;
cout << s3.CStr() << endl;
String s4;
// s4 = s1;
cout << s4.CStr() << endl;
}
int main()
{
Test();
system("pause" );
return 0;
}
本文出自 “言安阳” 博客,谢绝转载!