Yesterday, the senior again out of the test test, let us implement similar to the string class of No mystring class, at first very headache, but really in the writing code when I was very excited to find that this process is really a very valuable opportunity, let me have the opportunity to be very good familiar with the review of C + + a lot of knowledge-class design , constructs destructors, member functions, friend functions, references, overloads, string manipulations, dynamic memory distributions ... So yesterday spent half a day to write more than 300 lines of code, and seriously carried out the relevant testing, modification and summary. Because the content is a little rich, so want to write out several times, the level of clarity.
Class space allocation: The class assigns its own space to each object to store its data members, and all objects are manipulated by the public access class method. At the same time in the object's independent space, does not include the data member dynamically allocates the space, the object only records the dynamic allocation space the address (therefore, when the destructor calls only deletes the image space, simultaneously needs to use new to delete dynamically assigns the address).
First, the class declaration-mystring.h:
1. Constructor function:
specifically for building new objects, allocating the necessary memory space to member data and assigning values to member data for new objects.
Default constructor:
The constructor that is used to create an object when an explicit initialization value is not provided (so it generally has no parameters)
Copy constructor:
Used to copy an object to a newly created object (the copied object must already exist, of course).
MyString (const MyString &STR);
Given a constructor for a certain initialization parameter:
The values in the argument list are assigned to each member function of the newly created object at once:
MyString (const CHAR*STR);
2. destructor function:
deletes the memory space occupied by an object when it expires, and when the object is created with the memory of the new request empty, call Delete at the same time in the destructor to release the original allocated memory space to prevent memory leaks.
~mystring ();
3. member function:
overloaded Assignment member function:
MyString &operator= (const MyString &STR); Using an existing string object to assign a value to an object
MyString &operator= (const CHAR*STR); Assigning directly with a constant string
General assignment function:
MyString &assign (const MYSTRING&STR);
MyString &assign (const CHAR*SSTR);
Several member functions that handle strings:
size_t getsize () const; Returns the string size
void clear (); //Empty the string
bool Empty (); Determines whether the string is empty
void swap (MyString &str); Swap two string
int compare (const MyString &str) const; Compare the size of 2 strings
//The first const indicates that the explicitly called string cannot be changed, and the const outside the parentheses indicates that the implicitly called string is immutable, read-only data
int compare (const CHAR*STR);
Append function:
MyString &operator+= (const MYSTRING&STR);
MyString &operator+= (const CHAR*STR);
MyString &append (const MYSTRING&STR);
MyString &append (const char *STR);
To generate a string:
Generates a string, starting at the No. 0 position with the length n, or the length of the entire string if n exceeds the length
4. Friend function (operator overload):
A friend function is generally defined in a class declaration, and it does not belong to a class member function, but it can be accessed by all data members of a class as well as a class member function.
friend bool operator== (const MyString &str1,const MyString &str2);
friend BOOL operator== (const char *str,const MyString &STR2);
friend bool operator== (const MyString &str1,const MyString *str2);
friend bool Operator> (const MyString &str1,const MyString &str2);
friend bool Operator> (const char*str1,const MyString &str2);
friend bool Operator> (const MyString &str1,const char*str2);
There are also comparisons of <.
Friend MyString operator+ (const MyString &str1,const MyString &str2);
Friend MyString operator+ (const char*str1,const MyString &str2); Two strings are added
friend MyString operator+ (const MyString &str1,const char*str2);
Friend Ostream & operator<< (ostream &os,const MyString &str); Overloading of output command characters
5. Member Data variables:
char *string; pointer int length pointing to a string
; Length of string
static const int string_number = 0; Count the number of strings created
Second, the implementation of the. cpp file:
1. Constructors and Destructors:
Mystring::mystring ()
{
length = 0;
string = new char;
Char *s = "/0";
memcpy (string,s,1);
++string_number;
}
Mystring::mystring (const CHAR*STR)
{
length = strlen (str);
string = new char (length+1);
memcpy (string,s,length);
++string_number;
}
Mystring::mystring (MyString &str)
{
length = str.length;
string = str.string;
++string_number;
}
Mystring::~mystring ()
{
delete[]string;
--string_number;
}
A few points of attention:
1 The constructor must initialize all data members.
2) Note the corresponding to the left and right types when assigning pointers to strings.
The char *s represents a pointer to a string, and all the right must be a string constant "/0" instead of '/0 '.
3 A pointer can only point to one address and cannot point to two at a time.
After assigning the address to string, the next step is definitely to determine what is stored in the assigned address, so this time we are using strcpy () or
memcpy () puts the corresponding string into the address.
If it turns out that we do:
Mystring::mystring ()
{
length = 0;
string = new char;
string = "/0";
++string_number;
}
Then we're not going to find anything wrong when we compile and implement it, however, the destructor uses the delete "" to free memory so that the execution results are garbled because the string= "/0"
makes it point to a string and does not allocate memory space, so there is an error when it is released.
4) Important statements in a destructor delete "Don't forget
the destructor will only release the space allocated for the object when it is used, but the object's space only stores the address of the data member's allocated memory, so there is no free memory space for the data member
, you must use the delete [] to release, prevent memory leaks
2. member functions for overloaded operators:
MyString &mystring::operator+= (const mystring&str) {char *dest;
Dest = new Char[str.length+length+1];
memcpy (dest,string,length);
memcpy (dest+length,str.string,str.length+1);
delete[]string;
length = Length+str.length;
string = dest;
Return*this;
} MyString &mystring::operator+= (const char*str) {char *dest;
Dest = new Char[strlen (str) +length+1];
memcpy (dest,string,length);
memcpy (Dest+length,str,strlen (str) +1);
delete[]string;
string = dest;
return *this;
}//String assignment MyString &mystring::operator= (const MYSTRING&STR) {if (&str = = this) return *this;
delete[]string;
string = new Char[str.length];
memcpy (string,str.string,str.length);
length = Str.length;
return *this; }
A few of the problems noted by
are: in the
1) + = operation, the object that calls the function must have a final string length greater than its original length, so in this function call we must reassign the string to a
two string length and size of memory region. But because the function return value must be a reference to the original calling object, we define an intermediate variable pointer to store the 2
string merge results, finally release the original memory area of the string pointer, and then let it point to the merged string.
2) "=" The assignment operation must be different from the initialization of the constructor.
before using this method, the object must have at least a certain value by calling the constructor data member. So this time we first judge whether two objects are
equal. The same words return the original object, if unequal:
then the string length of two objects must be different. So we first release the memory space of the original string and then allocate the memory space based on the string length of the assignment object and copy the character
string memory back.
3. Several functions of string processing:
size_t mystring::getsize (MyString &str) {return strlen (str.string);
} void Mystring::clear () {length = 0;
while (string!= '/0 ') *string = '/0 ';
BOOL Mystring::empty () {return strlen (string) ==0;
int MyString:: compare (const MyString &str) {return compare (string,str.string);
} void Mystring::swap (MyString &str) {char *temp;
temp = string;
string = str.string;
str = temp;
} Mystring mystring::substr (sizez_t pos=0,size_t N) const {Mystring string;
delete[]string.string;
if (n>length) {string.length = length;
string.string = new Char[length+1];
memcpy (string.string,string,length+1);
return string;
length = n;
string.string = new Char[length+1];
memcpy (string.string,string,length+1);
return string; }
Several questions to note:
1 in the implementation of these functions, we can directly call the C language in a number of string processing <string.h> functions to implement
2 in the clear () function, note that only the characters of each memory region are set to 0 and cannot be freed by delete[] to free up memory space, which can be easily caused by a destructor
Two free memory space caused an error.
3 swap () to achieve the exchange of this function, we can directly define the middle variable pointer implementation, do not have to reallocate the memory space all to the dump, this for the destructor
is not affected by the destructor.
4. Friend function:
friend bool operator== (const MyString &str1,const MyString &str2) return
strcmp (str1.string,str2.string) = =0;
Friend MyString operator+ (const MyString &str1,const MyString &str2)
{MyString MyString
;
char *dest;
Dest = new Char[str1.length+str2.length+1];
memcpy (dest,str1.string,str1.length);
memcpy (dest+str1.length,str2.string,str2.length+1);
delete[]mystring.string;
mystring.string = dest;
Mystring.length = str1.length+str2.length;
return mystring;
}
Friend Ostream &operator<< (ostream &os,const MyString &str)
{
os<<str.string;
return OS;
}
Note that the problem is similar to the above, here is not repeated ~ ~ ~
Several other function implementations are basically similar ~