簡單string 類的實現

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class String
{
private:
    char *str;
public:
    String(const char *gets=NULL);
    String(const String &news);
    String& operator=(const String &news);
    bool operator==(const String &news);
    String& operator+=(const String &news);
    ~String();
    friend ostream &operator <<(ostream &out,String const& s);
    friend istream &operator >>(istream &in,String const& s);
};
String::String(const char *gets)
{
    cout<<"調用構造"<<endl;
    if(gets==NULL)
    {
        str=new char[1];
        *str='\0';
    }
    else
    {
        int len=strlen(gets);
        str=new char[len+1];
        strcpy(str,gets);
    }
}
String::String(const String &news)
{
    cout<<"調用拷貝"<<endl;
    str=new char(strlen(news.str)+1);
    strcpy(str,news.str);
}
String& String:: operator=(const String &news)
{
    cout<<"調用賦值"<<endl;
    if(this==&news)return *this;
    delete[] str;
    str=new char(strlen(news.str)+1);
    strcpy(str,news.str);
    return *this;
}
bool String:: operator==(const String &news)
{
    cout<<"調用等號"<<endl;
    if(this==&news)return 1;
    if(strcmp(str,news.str)==0)return 1;
    else return 0;
}
String& String::operator+=(const String &news)
{
    cout<<"調用+="<<endl;
    char *tmp;
    tmp=new char(strlen(news.str)+strlen(this->str)+1);
    strcpy(tmp,this->str);
    strcpy(tmp+strlen(this->str),news.str);
    delete[] str;
    str=tmp;
    return *this;
}
String::~String()
{
    cout<<"調用析構"<<endl;
    if(str!=NULL)delete[] str;
}
ostream &operator <<(ostream &out,String const& s)
{
    out<<s.str;
    return out;
}
istream &operator >>(istream &in,String const& s)
{
    in>>s.str;
    return in;
}
int main()
{
    String a;
    cin>>a;
    cout<<a<<endl;
    String b("123");
    cout<<b<<endl;
    String c=b;
    cout<<c<<endl;
    if(b==c)cout<<"拷貝成功"<<endl;
    a=b;
    if(b==a)cout<<"賦值成功"<<endl;
    cout<<"flag"<<endl;
    a="333";
    cout<<"flag"<<endl;
    a+=b;
    cout<<a<<endl<<b<<endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章