#include
using namespace std;
class MyString{
private:
char* Buffer;
public:
MyString( const char* InititalInput )
{
if (InititalInput != NULL)
{
Buffer = new char[ strlen( InititalInput ) + 1 ];
strcpy_s( Buffer, strlen( InititalInput ) + 1, InititalInput );
}
else
Buffer = NULL;
}
~MyString()
{
if (Buffer != NULL)
delete []Buffer;
Buffer = NULL;
}
MyString( const MyString& CopySource )
{
if (CopySource.Buffer != NULL)
{
if (Buffer != NULL)
{
delete[]Buffer;
Buffer = NULL;
}
Buffer = new char( strlen( CopySource.Buffer ) + 1 );
strcpy_s( Buffer, strlen( CopySource.Buffer ) + 1, CopySource.Buffer );
}
else
Buffer = NULL;
}
MyString& operator=( const MyString& CopySource )
{
if (( this != &CopySource ) && ( CopySource.Buffer != NULL ))
{
if (Buffer != NULL)
{
delete[]Buffer;//錯誤提示是CRT detected that the application wrote to memory after end of heap buffer
Buffer = NULL;//這種錯誤是由於內存操作不當造成的,可是String3之前的使用中內存分配沒少分配
} //delete[]Buffer也還沒執行
Buffer = new char( strlen( CopySource.Buffer ) + 1 );
strcpy_s( Buffer, strlen( CopySource.Buffer ) + 1, CopySource.Buffer );
}
return *this;
}
operator const char*( )
{
return Buffer;
}
};
int main()
{
MyString String1( " Hello " ), String2( " World " );
MyString String3( String1 );
cout << String1 << String2 << endl;
cout << String3 << endl;
String3 = String2;
cout << String3 << endl;
return 0;
}
錯誤已發現new char[]括號打成了()