c++运算符重载

仿照string类,完成myString 类

#include <iostream>
#include <cstring>
#define MAX 10
using namespace std;
class myString
{
private:
    char *str;
    int size;
public:
    //无参构造
    myString():str(new char[MAX]),size(MAX)
    {
        strcpy(str, "");
        cout<<"无参构造"<<endl;
    }
    //有参构造
    myString(const char *s)
    {
        this->size = strlen(s);
        this->str = new char[size+1];
        strcpy(str, s);
        cout<<"有参构造"<<endl;

    }
    //拷贝构造
    myString (const myString &other):str(new char[other.size+1]),size(other.size)
    {
        strcpy(this->str, other.str);
        cout<<"拷贝函数"<<strlen(str)<<endl;
    }
    //析构函数
    ~myString()
    {
        delete [] str;
        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];
            strcpy(str, other.str);
        }
        cout<<"拷贝赋值函数"<<strlen(str)<<endl;
        return *this;
    }
    //判空函数
    bool mystring_empty()
    {
        if(strlen(str) == 0)
        {
            return true;
        }
        return false;
    }
    //size函数
    void mystring_size()
    {
        if(mystring_empty() == true)
        {
            cout<<"实际长度为size ="<<strlen(str)<<endl;
            return ;
        }
        cout<<"实际长度为size =  "<<strlen(str)<<endl;
        return ;
    }
    //c_str函数
    const char* c_str(myString s)const
    {
        char *ptr = new char[s.size+1];
        strcpy(ptr, str);
        return ptr;
    }
    //at函数

    //cahr &at(int pos)
    //加号运算符重载
    const myString operator+(const myString &s1)
    {
        int newsize = this->size+s1.size;
        char *ptr = new char[newsize+1];
        strcpy(ptr, str);
        strcat(ptr, s1.str);
        cout<<ptr<<endl;
        return ptr;
    }
    //加等于运算符重载
    myString &operator+=(const myString &other)
    {
        int newsize = this->size+other.size;
        char *newptr = new char[newsize+1];
        strcpy(newptr, other.str);
        strcat(newptr, str);
        cout<<newptr<<endl;
        return *this;
    }
    //关系运算符重载(<)
    //中括号运算符重载


};
int main()
{
    myString s1("hello world");
    myString s2 = s1;
    myString s3("chen");
    myString s4 = s3;
    s4+=s1;
    myString s5;
    s5=s2+s1;
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值