2023年10月3日

C++运算符重载实现的过程

#include 
#include 

using namespace std;

class mystring
{
private:
    char *str;
    int size;
public:
    //无参构造
    mystring():size(10)
    {
        str = new char[size];
        strcpy(str,"");
        cout<<"无参构造"<size=other.size;
        this->str=new char[this->size];
        strcpy(this->str,other.str);

        cout<<"拷贝构造"<str,other.str);
            this->size=other.size;

            //判断原来指针空间释放被清空
            if(this->str !=NULL)
            {
                delete this->str;
            }
            this->str=new char(*other.str);
        }
        cout<<"mystring::拷贝赋值函数"<size==0);
    }

    //size函数
    int str_size()
    {
        return strlen(this->str);
    }

    //c_str函数
    char *myc_str()
    {
        return str;
    }


    //at函数
    char &at(int pos)
    {
        return *(this->str+pos-1);
    }

    //加号运算符重载
    mystring operator+(const mystring &r)const
    {
        mystring s1;
        strcat(s1.str,this->str);
        strcat(s1.str,r.str);
        s1.size=this->size+r.size;
        return s1;
    }


    //加等于运算符重载
    mystring* operator+=(const mystring&r)
    {
        strcat(this->str,r.str);
        this->size+=r.size;
        return this;
    }

    //关系运算符重载(>)
    bool operator>(const char* &r)const
    {
        if(strcmp(this->str,r)<=0)
        {
            return 0;
        }
        return 1;
    }

    //中括号运算符重载
    char &operator[](int index)const
    {
        return this->str[index-1];
    }

    friend void show(const mystring str);
};

void show(const mystring s)
{
    cout<

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