String类
时间:2010-08-10 来源:wsnhyjj
#include <iostream>
using namespace std;
class String { private: char *m_string; public: String(const char *str=NULL); String(const String &other); ~String(void); String &operator=(const String &other); void display() { cout<<m_string<<endl; } };
String::String(const char*str) { cout<<"Constructing..."<<endl; if(NULL==str) { m_string=new char[1]; *m_string='\0'; } else { m_string=new char[strlen(str)+1]; strcpy(m_string,str); } }
String::~String(void) { cout<<"Destructing..."<<endl; if(NULL!=m_string) { delete []m_string; m_string=NULL; } }
String::String(const String &other) { cout<<"Copy Constructing.."<<endl; m_string=new char[strlen(other.m_string)+1]; strcpy(m_string,other.m_string); }
String & String::operator =(const String &other) { cout<<"Operate = Function..."<<endl; if(&other==this) { return *this; } else { delete []m_string; m_string=new char[strlen(other.m_string)+1]; strcpy(m_string,other.m_string); return *this; } }
int main() { String string1("Hello"); string1.display();
String string2("World"); string2.display();
String string3(string1); string3.display();
string3=string2; string3.display(); return 0; }
class String { private: char *m_string; public: String(const char *str=NULL); String(const String &other); ~String(void); String &operator=(const String &other); void display() { cout<<m_string<<endl; } };
String::String(const char*str) { cout<<"Constructing..."<<endl; if(NULL==str) { m_string=new char[1]; *m_string='\0'; } else { m_string=new char[strlen(str)+1]; strcpy(m_string,str); } }
String::~String(void) { cout<<"Destructing..."<<endl; if(NULL!=m_string) { delete []m_string; m_string=NULL; } }
String::String(const String &other) { cout<<"Copy Constructing.."<<endl; m_string=new char[strlen(other.m_string)+1]; strcpy(m_string,other.m_string); }
String & String::operator =(const String &other) { cout<<"Operate = Function..."<<endl; if(&other==this) { return *this; } else { delete []m_string; m_string=new char[strlen(other.m_string)+1]; strcpy(m_string,other.m_string); return *this; } }
int main() { String string1("Hello"); string1.display();
String string2("World"); string2.display();
String string3(string1); string3.display();
string3=string2; string3.display(); return 0; }
相关阅读 更多 +