要求这个类包括
1.Write your first class named mystring
2.Constructor,destructor(at least three constructer)
3.Deep copy
4.Integrate your previous functions such as upper(),lower() into this class.
要求这个类包括
1.Write your first class named mystring
2.Constructor,destructor(at least three constructer)
3.Deep copy
4.Integrate your previous functions such as upper(),lower() into this class.
#include<iostream> using namespace std;
class mystring;//declaration of mystring
ostream &operator<<(ostream &out,const mystring &s);// declaration of function operator<<
class mystring { public: mystring()//constructor function 1 { m_pstr=NULL; } mystring(const char *p)//constructor function 2 { m_pstr=new char[strlen(p)+1]; strcpy(m_pstr,p); } mystring(const mystring &s)//constructor function 3<===>deep copy { m_pstr=new char[strlen(s.m_pstr)+1]; strcpy(m_pstr,s.m_pstr); } mystring &operator=(const mystring &s)//overload operator= { delete []m_pstr; m_pstr=new char[strlen(s.m_pstr)+1]; strcpy(m_pstr,s.m_pstr); return *this; } mystring &operator+=(const mystring &s)//overload operator+= { char *pTemp=new char[strlen(m_pstr)+1]; strcpy(pTemp,m_pstr); delete []m_pstr; m_pstr=new char[strlen(pTemp)+strlen(s.m_pstr)+1]; strcpy(m_pstr,pTemp); strcat(m_pstr,s.m_pstr); return *this; } mystring operator+(const mystring &s)//overload operator+ { mystring Test; Test.m_pstr=new char[strlen(m_pstr)+strlen(s.m_pstr)+1]; strcpy(Test.m_pstr,m_pstr); strcat(Test.m_pstr,s.m_pstr); return Test; } friend ostream &operator<<(ostream &out,const mystring &s);//friend operator<< ~mystring()//destructor function { delete []m_pstr; m_pstr=NULL; } private: char *m_pstr; };
ostream &operator<<(ostream &out,const mystring &s) { out<<s.m_pstr; return out; }
int main() { mystring Test1="Hello "; mystring Test2="World!"; mystring Test3=Test1+Test2; cout<<Test3<<endl; return 0; }
That's all, if you need more functions,call me~