C++仿照标准字符串类string,设计一个自己的字符串类String

主要完成以下任务:
1)数据成员是字符指针,可自动适应不同的串长度。
2)串复制,既可使用字符串常量进行复制,也可以使用其他的字符串对象进行复制。
3)串赋值。既可赋值为字符串常量,也可以赋值为使用其他的字符串对象。
4)串连接。重载“+”和“+=”。
5)重载下标运算符[]。
6)串比较。重载“==”和“<”。
7)字符串输入和输出。重载“>>”和“<<”。
程序重点在于运算符重载,以及解决空指针,自赋值问题!
改进,可将字符串长度定义为数据成员,这样就不用每次都用strlen计算长度!若需要定义为数据成员的代码,私我!
程序代码:

#include<iostream>
#include<cstring>
using namespace std;
class String {
private:
    char * Pstr;
public:
    String(const char* p = NULL) {
        if (p == NULL) {
            Pstr = new char[1];
            *Pstr = '\0';
        } else {
            Pstr = new char[strlen(p) + 1];
            strcpy(Pstr, p);
        }
    }

    String(const String& s): Pstr(new char[strlen(s.Pstr) + 1]) {
        strcpy(Pstr, s.Pstr);
    }

    ~String() {
        if (Pstr)
            delete[] Pstr;
    }
    String& operator=(const String& s) {
        if (Pstr == s.Pstr)
            return *this;
        else if (NULL == this) {
            delete Pstr;
            Pstr = new char[strlen(s.Pstr) + 1];
            strcpy(Pstr, s.Pstr);
        } else {
            strcpy(Pstr, s.Pstr);
        }
        return *this;
    }

    friend ostream & operator<<(ostream &out, const String &s) {
        out << s.Pstr;
        return out;
    }

    friend istream & operator >>(istream &in, String &s) {
        in >> s.Pstr;
        if(in)
            return in;
    }

    String operator+(const String &s2) {
        char *p=new char[strlen(Pstr) + strlen(s2.Pstr)+1];
        p=strcat(Pstr,s2.Pstr);
        return String(p);
    }
    void operator+=(const String &s2) {
        strcat(Pstr, s2.Pstr);
    }
    char& operator[](int n) {
        return Pstr[n];

    }
    int Length() {
        int n=strlen(Pstr) ;
        return n;
    }
    bool operator==(const String &s2) {
        return strcmp(Pstr, s2.Pstr) == 0;
    }
    bool operator<(const String &s2) {

        return strcmp(Pstr, s2.Pstr) < 0;
    }
};

提供一个main测试函数

int main() {
    String s1("Help"), s2("Good"), s3(s2), s4, s5;
    cout << "s1=" << s1 << endl;
    s3 = "Hello!";
    cout << "s3=" << s3 << endl;
    s3 = s2;
    cout << "s3=" << s3 << endl;
    s3 += s2;
    cout << "s3=" << s3 << endl;
    cin >> s4;
    cout << "s4=" << s4 << endl;
    s5 = s3 + s4;
    cout << "s5=" << s5 << endl;
    s5[0] = 'g';
    cout << "s5=" << s5 << endl;
    cout << "strlen(s5)=" << s5.Length() << endl;
    cout << boolalpha << (s3 == s1) << endl;
    cout << boolalpha << (s3 < s1) << endl;
    return 0;
}

运行截图
在这里插入图片描述
有收获的小可爱记得点关注哦!嘿嘿!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值