简单string 类的实现

#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
class String
{
private:
    char *str;
public:
    String(const char *gets=NULL);
    String(const String &news);
    String& operator=(const String &news);
    bool operator==(const String &news);
    String& operator+=(const String &news);
    ~String();
    friend ostream &operator <<(ostream &out,String const& s);
    friend istream &operator >>(istream &in,String const& s);
};
String::String(const char *gets)
{
    cout<<"调用构造"<<endl;
    if(gets==NULL)
    {
        str=new char[1];
        *str='\0';
    }
    else
    {
        int len=strlen(gets);
        str=new char[len+1];
        strcpy(str,gets);
    }
}
String::String(const String &news)
{
    cout<<"调用拷贝"<<endl;
    str=new char(strlen(news.str)+1);
    strcpy(str,news.str);
}
String& String:: operator=(const String &news)
{
    cout<<"调用赋值"<<endl;
    if(this==&news)return *this;
    delete[] str;
    str=new char(strlen(news.str)+1);
    strcpy(str,news.str);
    return *this;
}
bool String:: operator==(const String &news)
{
    cout<<"调用等号"<<endl;
    if(this==&news)return 1;
    if(strcmp(str,news.str)==0)return 1;
    else return 0;
}
String& String::operator+=(const String &news)
{
    cout<<"调用+="<<endl;
    char *tmp;
    tmp=new char(strlen(news.str)+strlen(this->str)+1);
    strcpy(tmp,this->str);
    strcpy(tmp+strlen(this->str),news.str);
    delete[] str;
    str=tmp;
    return *this;
}
String::~String()
{
    cout<<"调用析构"<<endl;
    if(str!=NULL)delete[] str;
}
ostream &operator <<(ostream &out,String const& s)
{
    out<<s.str;
    return out;
}
istream &operator >>(istream &in,String const& s)
{
    in>>s.str;
    return in;
}
int main()
{
    String a;
    cin>>a;
    cout<<a<<endl;
    String b("123");
    cout<<b<<endl;
    String c=b;
    cout<<c<<endl;
    if(b==c)cout<<"拷贝成功"<<endl;
    a=b;
    if(b==a)cout<<"赋值成功"<<endl;
    cout<<"flag"<<endl;
    a="333";
    cout<<"flag"<<endl;
    a+=b;
    cout<<a<<endl<<b<<endl;
    return 0;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值