华清远见第六课程day4作业

仿照string类,完成myString 类


#include <iostream>
#include <cstring>

using namespace std;

class myString{
private:
    char *str;
    int size;
public:
    myString():size(10){
        str = new char[size];
        strcpy(str,"");
    }
    myString(const char*s){
        size = strlen(s);
        str = new char[size+1];
        strcpy(str,s);
    }
    //拷贝构造
    myString(const myString &other):str(new char(*other.str)),size(other.size){
        cout<<"拷贝构造"<<endl;
    }
    //析构函数
    ~myString(){
        delete str;
        cout<<"析构函数"<<this<<endl;
    }
    //拷贝赋值函数
    myString & operator=(const myString &other)
        {
            if(this != &other)          //确定不是自己给自己赋值
            {
                this->size = other.size;

                //判断原来指针空间释放被清空
                if(this->str != NULL)
                {
                    delete this->str;
                }
                this->str = new char(other.size);
                strcpy(str,other.str);

                //如果指针空间大小一致  //*this->ptr = *other.ptr;
            }
            cout<<"Stu:: 拷贝赋值函数"<<endl;
            return  *this;             //返回自身引用
        }
    void show(){
        cout<<size<<endl;
        cout<<str<<endl;
    }
    //判空函数
    int empty(){
        return str[1]==0;
    }
    //size函数
    int getsize(){
        int i=0;
        while(*(str+i)){
            i++;
        }
        size = i;
        return i;
    }
    //c_str函数
    const char* c_str(){
        return str;
    }
    //at函数
    char &at(int pos){
        if(pos<0||pos>size){
            cout<<"输入的位置有误请重新输入"<<endl;
        }
        return *(str+pos);
    }
    friend const myString operator +(const myString &L,const myString &R);
    //加等于运算符重载
    myString & operator += (const myString &R){
        strcat(this->str,R.str);
        this->size+=R.size;
        return *this;
    }
    //关系运算符重载(>)
    bool operator > (const myString &R)const{
        return strcmp( this->str,R.str);
    }
    //中括号运算符重载
    char & operator[](int i){
        if(i<=size&&i>=0){
            return *(str+i);
        }
    }
};
//加号运算符重载
const myString operator+(const myString &L,const myString &R){
    myString c;
    strcpy(c.str,L.str);
    strcat(c.str,R.str);
    c.size=R.size+L.size;
    return c;
}





int main()
{
    myString str("114514");
    myString str1("1919810");
    myString str3=str+str1;
    myString str4;
    str4=str;
    str4+=str1;
    str4[6]='a';
    if(str>str1){
        cout<<"大"<<endl;
    }
    else{
        cout<<"小"<<endl;
    }
    str4.show();
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值