C++简易封装自己的string类

在C++中,string是一种常用的类,相较于C语言的字符数组和字符串指针,string对于字符串的操作更加简单。

1.定义Mystring类

#include <iostream>
#include <cstring>
#include <cassert>
using namespace std;

class Mystring{
    public:
        Mystring()//默认构造函数
        {
                data=new char [1];
                *data='\0';
        }

        Mystring(const char *s)//构造函数有参数
        {
            //如果有字符串,则创建比字符串大一个的空间,并复制给类成员变量
                int len;
                len = strlen(s);
                data=new char[len+1];
                assert(NULL != data);
                strcpy(data,s);
        }
        Mystring(const Mystring &my)//拷贝构造函数
        {
                int len;
                len = strlen(my.data);
                data=new char[len+1];
                assert(NULL != my.data);
                strcpy(data,my.data);
        }
        ~Mystring()//析构函数
        {
            delete [] data;

        }
    public:
        char getval()
        {
            return *data;
        }

        bool operator ==(const Mystring &);
        Mystring & operator =(const Mystring &);
        Mystring & operator +(const Mystring &);

    friend ostream & operator <<(ostream &,Mystring &);
    friend istream & operator >>(istream &,Mystring &);
    private:
        char *data;
};

2.类操作

//输出流运算符重载
ostream & operator <<(ostream &os,Mystring &my)
{
    os << my.data;
    return os;
}
//输入流运算符重载
istream & operator >>(istream &os,Mystring &my)
{
    os >> my.data;
    return os;
}
//==运算符重载
bool Mystring::operator ==(const Mystring &my)
{
    if(0 == strcmp(this->data,my.data))
        return true;
    else
        return false;
}
//=运算符重载
Mystring & Mystring::operator =(const Mystring &my)
{
    if(*this == my)
        return *this;
    delete this->data;
    int len;
    len = strlen(my.data);
    this->data=new char[len+1];
    strcpy(this->data,my.data);
    return *this;
}
//+运算符重载
Mystring & Mystring::operator +(const Mystring &my)
{
    int len;
    char *temp;
    len = strlen(this->data)+strlen(my.data);
    temp = new char [len+1];
    assert(NULL != temp);
    strcpy(temp,this->data);
    strcat(temp,my.data);
    delete this->data;
    this->data = temp;
    return *this;
}

3.测验

int main()
{
    Mystring a="hello";
    Mystring b;
    b=a;
    cout << "a:"<< a << endl;
    cout << "b:"<< b << endl;
    cout <<"a+b:"<<(a+b)<<endl;
    cout <<"a?=b:"<<(a==b)<<endl;
    Mystring c;
    cout<<"c:";
    cin>>c;
    cout<<"b+c:"<<(b+c)<<endl;
    return 0;
}

输出结果:

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值