day40

#include <iostream>
#include <cstring>
using namespace std;
class mystring;
void null(mystring &s);
void size(mystring &s);
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);
        cout<<"有参构造"<<endl;
    }
    //拷贝构造
    mystring(const mystring &other):str(new char(*other.str)),size(other.size)
    {
        cout<<"拷贝构造函数"<<endl;
    }
    //析构函数
    ~mystring()
    {
        cout<<"析构函数"<<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.str);
        }
        cout<<"拷贝赋值函数"<<endl;
        return *this;
    }
    //判空函数
    friend void null(mystring &s);
    //size函数
    friend void size(mystring &s);
    //c_str函数
    void c_str(mystring &s)
    {
        cout<<"str="<<s.str<<endl;
    }
    //at函数
    char &at(int pos);
    //加号运算符重载
    const mystring  operator+(const mystring &R)const
    {
        mystring c;
        c.str=strcat(str,R.str);
        c.size=this->size + R.size;
        return c;
    }
    //加等于运算符重载
    mystring & operator+=(const mystring &R)
    {
        strcat(this->str,R.str);
        this->size+=R.size;
        return *this;
    }
    //关系运算符重载(>)
    bool operator>(const mystring &other)const
    {
        if(strcmp(str,other.str)>0)
        {
            return true;
        }
        return false;
    }

    //中括号运算符重载
    char & operator[](int i)
    {
        if(i >= 0 && i< size)
        {
            return this->str[i];
        }
        else
        {
            cout<<"数组越界"<<endl;
        }
    }
};
void null(mystring &s)
{
    if(s.size==0)
    {
        cout<<"空字符串"<<endl;
    }
    cout<<"不是空字符串"<<endl;
}
void size(mystring &s)
{
    cout<<"size="<<s.size<<endl;
}
int main()
{
    mystring s("new");
    null(s);
    size(s);
    s.c_str(s);
    mystring s1("hello");
    mystring s2=s1+s;
    size(s2);
    s2.c_str(s2);
    mystring s3("world");
    s3+=s2;
    size(s3);
    s3.c_str(s3);
    if(s3>s1)
    {
        cout<<"s3>s1"<<endl;
    }else
    {
        cout<<"s3<=s1"<<endl;
    }

    cout<<s3[6]<<endl;
    return 0;
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值