嵌入式开发学习(C++篇)第三天2023/3/29

string函数自定义

#include 
#include 

using namespace std;

//string
class mystring{

private:
    char *str;  //记录C风格字符串
    int len;   //记录字符串实际长度

public:
    //无参构造
    mystring(): len(10){
        str = new char[len];
        str[0] = '\0';
    }
    //有参构造
    mystring(const char *s): len(strlen(s)){
        str = new char[len+1];
        strcpy(str, s);
    }
    //拷贝构造
    mystring(const mystring &other): len(other.len){
        str = new char[len+1];
        strcpy(str, other.str);
    }
    //拷贝赋值
    mystring &operator = (const mystring &other){
        if(this == &other){
            return *this;
        }
        delete []str;
        len = other.len;
        str = new char[len+1];
        strcpy(str, other.str);
        return *this;
    }
    //析构函数
    ~mystring(){
        delete []str;
    }
    //判空函数
    bool empty(){
        return (0 == len);
    }
    //size函数
    int size()const{
        return len;
    }
    //c_str函数
    const char *c_str(){
        return str;
    }
    //at函数
    char &at(int pos)const{
        try{
            //合法性检查
            if(pos >= len || pos < 0){
                throw "输入下标不合法";
            }
            return str[pos];
        }
        catch(const char *e){
            cerr << e << "是错误输入" << endl;
            exit(1);
        }
    }
    //[]运算符
    char &operator[](const int &pos){
        try{
            //合法性检查
            if(pos >= len || pos < 0){
                throw "输入下标不合法";
            }
            return str[pos];
        }
        catch(const char *e){
            cerr << e << "是错误输入" << endl;
            exit(1);
        }
    }
    //+运算符
    mystring &operator+(const mystring &other){
        int l = this->len+other.len+1;
        mystring *temp = new mystring;
        delete []temp->str;
        temp->len = l;
        temp->str = new char[l];
        strcat(temp->str, this->str);
        strcat(temp->str, other.str);
        return *temp;
    }
    bool operator==(const mystring &R)const{
        if(this->len != R.len)
            return  false;
        for(int i=0; iat(i) != R.at(i))
                return false;
        return true;
    }
    friend ostream &operator<<(ostream &L, mystring &R);
    friend istream &operator>>(istream &L, mystring &R);
    friend void mygetline(istream &L, mystring &R);
};
//<<运算符
ostream &operator<<(ostream &L, mystring &R){
    L << R.str << endl;
    return L;
}
//>>运算符
istream &operator>>(istream &L, mystring &R){
    cin >> R.str;
    return L;
}
//getline
void mygetline(istream &L, mystring &R){
    gets(R.str);
}

int main()
{
    return 0;
}

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