The prototype of the String class is as follows
Class String
{
Public
String (const char *str=null); constructor function
String (const string &other); Copy constructor
~string (void); Destructors
string& operator= (const String &other); equals operator overloading
Showstring ();
Private
Char *m_data; Pointer
};
String::~string ()
{
delete [] m_data;//destructor, release address space
}
string::string (const Char *str)
{
if (str==null)//When the initialization string does not exist, request a space for the m_data to hold ' n ';
{
m_data=new char[1];
*m_data= ' + ';
}
else//When the initialization string exists, for m_data to apply the same size space to store the string;
{
int Length=strlen (str);
m_data=new char[length+1];
strcpy (M_DATA,STR);
}
}
string::string (const String &other)//copy constructor, function similar to constructor function.
{
int Length=strlen (other.m_data);
M_data=new [length+1];
strcpy (M_data,other.m_data);
}
string& String::operator = (const String &other)
{
if (this==&other)//When the address is the same, return directly;
return *this;
Delete [] m_data;//when the address is not the same, delete the original application of space, re-start construction;
int length= strlen (other.m_data);
M_data=new [length+1];
strcpy (M_data,other.m_data);
return *this;
}
String::showstring ()//Because M_data is a private member, the object can only be accessed through the public member function;
{
cout<<this->m_data<<endl;
}
Main ()
{
String AD;
char * p= "ABCDE";
String B (P);
AD. Showstring ();
Ad=b;
AD. Showstring ();
}
1. The Strcopy function can be a standard library function char *strcpy (char *dest, const char *SRC);
Need #inculde <string.h>
2. Reference Connection:
High quality C++c Programming Guide http://man.chinaunix.net/develop/c&c++/c/c.htm
String function http://www.ggv.com.cn/forum/clib/string/strcpy.html
constructor, copy constructor, and destructor for class string