最も簡単なstringクラスの深いコピーを実現
1645 ワード
#include
using namespace std;
class String
{
public:
String()
:_str( new char [1])
{
_str = '\0';
}
String( const char * str)
:_str( new char [strlen(str) + 1])
{
strcpy( this->_str ,str);
}
String( const String& str)
:_str( new char [strlen(str._str) + 1])
{
strcpy( this->_str ,str._str);
}
~String()
{
delete []_str;
}
String& operator= (const String& str)
{
String tmp(str);
swap( this->_str ,tmp._str );
return *this ;
}
void Display()
{
printf( "%s
",_str);
}
private:
char *_str;
};
void test1()
{
String s1( "change world");//
s1.Display();
String s2 = s1; //
s2.Display();
String s3;
s3.Display();
s3 = s1; //
s3.Display();
}
int main()
{
test1();
system( "pause");
return 0;
}