C++的String类简单实现

String类实现,构造函数,初始化函数,析构函数,重载=,+=运算符,定义友元函数+,<<运算符,SubStr子串函数。

#include
#include
using namespace std;

class String
{
    private:
        char* str;
        int length;
    public:
        String();
        String(const char* other);
        String(const String &other);
        ~String();
        String &operator=(const String &other);
        String &operator+=(const String &other);
        char *SubStr(int pos,int len);
        friend String &operator+ (const String &s1,const String &s2);
        friend ostream &operator<< (ostream &out,const String &other);

};
String::String()
{
    str=new char[1];
    str[0]='\0';
}
String::String(const char* other){
    int len=strlen(other);
    str=new char[len];
    length=len;
    strcpy(str,other);
}
String::String(const String &other)
{
    int len=strlen(other.str);
    str=new char[len];
    length=len;
    strcpy(str,other.str);
    cout << "拷贝构造" <<endl;
}

String::~String()
{
    delete[] str;
}
String &String::operator=(const String& other)
{
    cout << "赋值重载"<<endl;
    if(this==&other)
    {
        return *this;
    }
    int len=strlen(other.str);
    str = new char[len];
    length=len;
    strcpy(str,other.str);
    return *this;
}

String &String::operator+= (const String &other)
{
    char* tmp;
    int len=strlen(other.str);
    tmp=new char[length+len];
    length+=len;
    strcpy(tmp,str);
    strcat(tmp,other.str);
    strcpy(str,tmp);
    return *this;
}
String &operator+ (const String &s1,const String &s2)
{
    String tmp;
    int len1=strlen(s1.str);
    int len2=strlen(s2.str);
    tmp.length=len1+len2;
    tmp.str=new char[len1+len2];
    strcpy(tmp.str,s1.str);
    strcat(tmp.str,s2.str);
    return tmp;

}
ostream &operator<<(ostream &out,const String &other)
{
    out << other.str;
    return out;
}
char *String::SubStr(int pos,int len)
{
    char *tmp=new char[length];
    int k=0;
    for(int i=pos;i<pos+len;i++)
    {
        tmp[k++]=str[i];
    }
    return tmp;
}
int main()
{
    String s1;
    String s2="hello";
    String s3="world";
    String t=s2;
    t+=s3;
    cout << t << endl;
    cout << t.SubStr(0,3)<<endl;
}

你可能感兴趣的:(综合笔记)