手写string类

#include <iostream>
#include <cstdio>
#include <cstring>

using namespace std;

class string_hui
{
private:
    char *str;
    int len;
public:
    string_hui();
    string_hui(const char *s);
    string_hui(const string_hui& s);
    string_hui& operator=(const string_hui& s);
    string_hui& operator=(const char *s);
    char& operator[](int i) ;
    const char& operator[](int i)const;
    friend ostream& operator<<(ostream &os,const string_hui &s);
    int length();
    char * getstr();
    ~string_hui();
};

string_hui::string_hui()
{
    str="hello";
    len=strlen(str);
}

string_hui::string_hui(const char *s)
{
    len=strlen(s);
    str=new char[len+1];
    strcpy(str,s);
}

 string_hui::string_hui(const string_hui& s)
 {
     len=s.len;
     str=new char[s.len+1];
     strcpy(str,s.str);
 }

 string_hui& string_hui::operator=(const string_hui& s)
 {
     if(this==&s)
        return *this;
     delete [] str;
     len=s.len;
     str=new char[s.len+1];
     strcpy(str,s.str);
     return *this;
 }

string_hui::~string_hui()
{
    delete [] str;
}

char& string_hui::operator[](int i)
{
    return str[i];
}

const char& string_hui::operator[](int i) const
{
    return str[i];
}

string_hui& string_hui::operator=(const char* s)
{
    delete [] str;
    len=strlen(s);
    str=new char[len+1];
    strcpy(str,s);
    return *this;
}

int string_hui::length()
{
    return len;
}

char* string_hui::getstr()
{
    return str;
}

ostream& operator<<(ostream &os,const string_hui &s)
{
    os<<s.str;
    return os;
}

int main()
{
    string_hui s1;
    cout<<s1.getstr()<<" "<<s1.length()<<endl;
    cout<<s1[2]<<endl;

    string_hui s2("huihui");
    cout<<s2.getstr()<<" "<<s2.length()<<endl;
    cout<<s2[1]<<endl;

    string_hui s3(s2);
    cout<<s3.getstr()<<" "<<s3.length()<<endl;
    cout<<s3[3]<<endl;

    string_hui s4=s1;
    cout<<s4.getstr()<<" "<<s4.length()<<endl;
    cout<<s4[2]<<endl;

    s4="nihao";
    cout<<s4.getstr()<<" "<<s4.length()<<endl;
    cout<<s4[2]<<endl;

    cout<<s4<<endl;
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值