Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
Objective
1. 2. 3. 4. 5. 6. 7. 8. 9. String Class Constructor Overloading Dynamic Memory Allocation User Defined append Function User Defined Length function Copy String Function Destructor. Operator overloading Copy Constructor
String Class
class MyString { char *p; int dlength; int capacity; };
Default constructor
MyString() { setlength(0); p = new char[capacity]; p[dlength]= '\0'; }
Constructor Overloading
MyString( char * cstr) { setlength(len(cstr)); p = new char[capacity]; copy(cstr); // copy function defined below p[dlength]= '\0'; }
Copy Function
void copy(char * cstr) { for(int i=0; i<dlength; i++) p[i] = cstr[i]; }
Length Function
int len(char * cstr) { int len=0; while(cstr[len]) { len++; } return len; }
Copy and length function are private. No one can access these functions directly.
These are public function for getting and setting of length in class.
Operator Overloading [ ]
char & operator [](int i) { return p[i]; }
Operator Overloading +=
void operator +=(MyString& s) { char *ms; capacity=dlength+s.length() +1;; ms=new char[capacity]; int index=0; for(int j=0; j<dlength; j++) { ms[j]=p[j]; index++;
Exercise 1
Write a function in class which concatenate two strings. Return a string object.
Destructor
~MyString() { delete [] p; }
Main Function
int main() { MyString s; MyString ss="hello"; MyString ss4="World"; //int n=ss.Len(); //cout<<ss.at(4); //cout<<ss[3]; ss[4]='5'; ss+=ss4; //system("pause"); return 0; }
Exercise 2
Write a function which compares two strings. Write a function which replace a set of characters in string from given index number.
Checked By: