C++中String类的实现

本文详细介绍了C++中自定义字符串类的实现过程,包括构造、赋值、比较、连接、复制等基本操作,并展示了如何使用友元函数进行流输入输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


#pragma once
#include <iostream>
#include <string.h>
#define _SIZE_ 100
using namespace std;
class Count
{
public:
    Count() :count(1){}
    void add()
    {
        count++;
    }
    void dec()
    {
        count--;
    }
    int getcount()
    {
        return count;
    }
private:
    int count;
};
class String
{
public:
    String(const char *s = "")
    {
        copy(ptr,s);
    }
    String(const String &s)
    {
        copy(ptr,s.ptr);
        counT.add();
    }
    String& operator=(const String& s)
    {
        if (this != &s)
        {
            String tmp(s.ptr);
            char *temp = tmp.ptr;
            tmp.ptr = ptr;
            ptr = temp;//内存安全。
        }
        return *this;
    }
    ~String()
    {
        if (counT.getcount() == 1)
        {
            cout << ptr << "  :del" << endl;
            delete[]ptr;
        }
    }
    friend ostream& operator<<(ostream& os, String &s)
    {
        os << s.ptr;
        return os;
    }
    friend istream& operator>>(istream& is, String &s)
    {
        char buf[_SIZE_];
        is >> buf;
        s.copy(s.ptr,buf);
        return is;
    }
    String& operator += (const String &s)
    {
        char *buf = new char[strlen(ptr) + strlen(s.ptr) + 1];
        strcpy(buf, ptr);
        strcat(buf,s.ptr);
        copy(ptr,buf);
        return *this;
    }
    String& operator +=(const char *str)
    {
        char *buf = new char[strlen(ptr) + strlen(str) + 1];
        strcpy(buf,ptr);
        strcat(buf,str);
        copy(ptr,buf);
        return *this;
    }
    bool operator != (const String &s)
    {
        return strcmp(ptr,s.ptr);
    }
    bool operator ==(const String &s)
    {
        return !strcmp(ptr,s.ptr);
    }
private:
    void copy(char *&p,const char *s)
    {
        p = new char[strlen(s) + 1];
        strcpy(p,s);
    }
private:
    char *ptr;
    Count counT;
};

#include <iostream>
#include "String.h"
using namespace std;
int main()
{
    String s("123");
    String s1("456");
    s += s1;
    return 0;
}

“`

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值