C++的String类简单实现

String类实现,构造函数,初始化函数,析构函数,重载=,+=运算符,定义友元函数+,<<运算符,SubStr子串函数。

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

class String
{
    private:
        char* str;
        int length;
    public:
        String();
        String(const char* other);
        String(const String &other);
        ~String();
        String &operator=(const String &other);
        String &operator+=(const String &other);
        char *SubStr(int pos,int len);
        friend String &operator+ (const String &s1,const String &s2);
        friend ostream &operator<< (ostream &out,const String &other);

};
String::String()
{
    str=new char[1];
    str[0]='\0';
}
String::String(const char* other){
    int len=strlen(other);
    str=new char[len];
    length=len;
    strcpy(str,other);
}
String::String(const String &other)
{
    int len=strlen(other.str);
    str=new char[len];
    length=len;
    strcpy(str,other.str);
    cout << "拷贝构造" <<endl;
}

String::~String()
{
    delete[] str;
}
String &String::operator=(const String& other)
{
    cout << "赋值重载"<<endl;
    if(this==&other)
    {
        return *this;
    }
    int len=strlen(other.str);
    str = new char[len];
    length=len;
    strcpy(str,other.str);
    return *this;
}

String &String::operator+= (const String &other)
{
    char* tmp;
    int len=strlen(other.str);
    tmp=new char[length+len];
    length+=len;
    strcpy(tmp,str);
    strcat(tmp,other.str);
    strcpy(str,tmp);
    return *this;
}
String &operator+ (const String &s1,const String &s2)
{
    String tmp;
    int len1=strlen(s1.str);
    int len2=strlen(s2.str);
    tmp.length=len1+len2;
    tmp.str=new char[len1+len2];
    strcpy(tmp.str,s1.str);
    strcat(tmp.str,s2.str);
    return tmp;

}
ostream &operator<<(ostream &out,const String &other)
{
    out << other.str;
    return out;
}
char *String::SubStr(int pos,int len)
{
    char *tmp=new char[length];
    int k=0;
    for(int i=pos;i<pos+len;i++)
    {
        tmp[k++]=str[i];
    }
    return tmp;
}
int main()
{
    String s1;
    String s2="hello";
    String s3="world";
    String t=s2;
    t+=s3;
    cout << t << endl;
    cout << t.SubStr(0,3)<<endl;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值