写一个string类

#ifndef MYSTRING_H_INCLUDED
#define MYSTRING_H_INCLUDED

#include <iostream>
#include <string.h>
using namespace std;

class String {
public:
    // constructor function
    String();  // default constructor function
    String(const String& s);  // copy constructor function
    String(const char* s);

    // overload function
    String& operator=(const String& s);  //
    String& operator=(const char* s);
    String& operator+=(const String& s);
    friend int operator==(const String& s1, const String& s2);
    friend int operator>(const String& s1, const String& s2);
    friend int operator<(const String& s1, const String& s2);
    char& operator[](int i);
    const char& operator[](int i) const;
    friend ostream& operator<<(ostream& os, String& s);
    friend istream& operator>>(istream& is, String& s);

    // common function
    int length() const
    {
        {
            return len;

        }
    };

    //
    ~String()
    {
        delete[]str;
    }

private:
    char* str;
    int len;
};



#endif // MYSTRING_H_INCLUDED
#include "String.h"
#include <string.h>

String::String()
{
	len = 0;
	str = new char[1];
	str[0] = '\0';

}

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

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

String& String::operator=(const String& s)
{
    // TODO: 在此处插入 return 语句
    if (this == &s)
    {
        return *this;
    }

    delete[]str;
    int len = s.length();
    str = new char[len + 1];
    strcpy(str, s.str);
    return *this;



}

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

    return *this;
}

String& String::operator+=(const String& s) {
    String c(*this);
    delete[]this->str;
    this->str = new char[this->length() + s.length()];
    stpcpy(this->str, c.str);
    stpcpy(this->str, s.str);
    this->len += s.length();
    delete[]c.str;

    return *this;
}

String& String::operator+=(const String& s) {
    String c(*this);
    delete[]this->str;
    this->str = new char[this->length() + s.length()];
    stpcpy(this->str, c.str);
    stpcpy(this->str, s.str);
    this->len += s.length();
    delete[]c.str;

    return *this;
}

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

istream& operator>>(istream& is, String& s) {
    char temp[80];
    cin.getline(temp, 80);
    //is >> temp;
    s = temp;

    return is;
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值