c++实现一个string类

#include
#include
using namespace std;

class String
{
private:
    char* data_;
    uint32_t length_;
public:
    String(const char* src=nullptr);
    String(const String& str);
    ~String(void);

    String& operator =(const String& other);
    String operator +(const String& other);
    String SubStr(int pos ,int len);
    void ShowString(void);

};

String::String(const char* src){
    if(src == nullptr){
        data_ = new char[1];
        *data_ = '\0';
        length_=1;
    }else{
        length_=strlen(src);
        data_=new char[length_+1];
        strcpy(data_,src);
    }
}

String::String(const String& str){
    length_ = str.length_;
    data_ = new char[length_+1];
    strcpy(data_,str.data_);
}

String::~String(void){
    delete [] data_;
}

String& String::operator=(const String& other){
    if(this == &other){
        return *this;
    }
    delete [] data_;
    length_ = other.length_;
    data_ = new char[length_+1];
    strcpy(data_,other.data_);
    return *this;
}

String String::operator+(const String& other){
    String tmp;
    delete tmp.data_;
    tmp.length_ = strlen(data_) + strlen(other.data_) + 1;
    tmp.data_ = new char[tmp.length_];
    strcpy(tmp.data_,data_);
    strcat(tmp.data_,other.data_);
    return tmp;
}

String String::SubStr(int pos,int len){
    String sub;

    if(pos+len > length_){
        sub.length_ = 13;
        sub.data_ = new char[len+1];
        strcpy(sub.data_,"out_of_range");
        return sub;
    }
    sub.length_ = len;
    sub.data_ = new char[len+1];
    strncpy(sub.data_,data_+pos,len);
    return sub;
}

void String::ShowString(void){
    cout << this->data_ << endl;
}


int main(){
    String s1;
    String s2("this is s2");
    String s3(s2);

    String s4 = s3;
    String s5 = s2+s3;
    String s6 = s2.SubStr(0,4);

    cout << "s1=" ;s1.ShowString();
    cout << "s2=" ;s2.ShowString();
    cout << "s3=" ;s3.ShowString();
    cout << "s4=" ;s4.ShowString();
    cout << "s5=" ;s5.ShowString();
    cout << "s6=" ;s6.ShowString();
    return 0;
}

c++实现一个string类_第1张图片

你可能感兴趣的:(c++,算法)