String类的实现

来源:互联网 发布:哈尔堡工业大学 知乎 编辑:程序博客网 时间:2024/06/11 21:01

因为大家对构造函数,拷贝构造函数和赋值运算符的区别可能有点模糊,这儿很详细的给出String类的实现,另一篇博文(拷贝构造函数和赋值运算符的区别)中写了三者的区别详细。

<span style="font-size:14px;">#include<iostream>using namespace std;class String{ public:        String(const char* str=NULL);   //普通构造函数        Strng(const String &other);     //拷贝构造函数        String & operator=(const String &other);  //赋值函数        ~String(void);                  //析构函数 public:        String & operator+(String &str);  //改变本身的相加        friend ostream& operator<<(ostream&out,String& s);        friend istream& operator>>(iostream&in,String& s);  private:        char *m_string ;              //保存字符串 };String::~String(void){  cout<<"destrcut"<<endl;  if(m_string!=NULL)                   //不为空,就释放内存 {   delete [] m_string;   m_string = NULL; }}String::String(const char* str)    //普通构造函数{ cout<<construct<<endl; if(str==NULL)        //如果str 为NULL,就存一个空字符串“”{  m_string=new char[1];  *m_string ='\0';}  else{  m_string = new char[strlen(str)+1] ;   //分配空间  strcpy(m_string,str);}} String::String(const String& other)   //拷贝构造函数{  cout<<"copy construct"<<endl;  m_string=new char[strlen(other.m_string)+1] ; //分配空间并拷贝 strcpy(m_string,other.m_string);}String & String::operator=(const String & other){cout<<"operator = funtion"<<endl ;if(this==&other) //如果对象和other是用一个对象,直接返回本身{return *this;}delete []m_string; //先释放原来的内存m_string = new char[strlen(other.m_string)+1];strcpy(m_string,other.m_string);return * this;}String & String::operator+(const String & str){ char * temp=m_string; m_string=new char[strlen(m_string)+strlen(str.m_string)+1]; strcpy(m_string,temp); delete[]temp; strcat(m_string,str.m_string); return *this;} ostream& operator<<(ostream& out,String& s){ for(int i=0;i<s.length();i++) out<<s[i]<<""; return out;}istream& operator>>(istream& in,String& s){ char p[50]; in.getline(p,50); s=p; return in;}int main(){String a("hello"); //调用普通构造函数String b("world"); //调用普通构造函数String c(a); //调用拷贝构造函数c=b; //调用赋值函数return 0;}


这儿实现这些必须的函数:构造函数,复制构造函数,赋值函数,析构函数,以及运算符重载

3 0
原创粉丝点击