实现C++自定义的String类

一、简介

  • 采用了COW写时复制的方式实现,即在每个String类数据域之前用了4个字节的空间进行引用计数。通过拷贝构造函数或者赋值运算符函数进行赋值时不会重新开辟空间,只会对引用计数加一,当有修改操作时,才会重新开辟新的空间;
  • 内部定义了一个char类型的内部代理类,用于解决String类重载下标运算符后无法区分读写操作的问题。

二、头文件

#pragma once
#include <iostream>


class String {
   
	class CharProxy {
    // char类型的代理内部类
	public:
		CharProxy(int index, String &str);
		char &operator=(const char &c);
		friend std::ostream &operator<<(std::ostream &os, const CharProxy &charPorxy);
	private:
		int _index;	   // 下标
		String &_this; // 指向外部类对象
	};

public:
	String();
	String(const char *pstr);
	String(const String &str);
	~String();
	String &operator=(const String &str);
	String &operator=(const char *pstr);

	String &operator+=(const String &str);
	String &operator+=(const char *pstr);
	
	String::CharProxy operator[](std::size_t index);
	
	std::size_t size()const; // 字符串的长度
	const char* c_str()const; // 返回一个C风格的字符串
	
	friend bool operator==(const String &leftStr, const String &rightStr);
	friend bool operator!=(const String &leftStr, const String &rightStr);
	
	friend bool operator<(const String &leftStr, const String &rightStr);
	friend bool operator>(const String &leftStr, const String &rightStr);
	friend bool operator<=(const String &leftStr, const String &rightStr);
	friend bool operator>=(const String &leftStr, const String &rightStr);
	
	friend std::ostream &operator<<(std::ostream &os, const String &str);
    friend std::istream &operator>>(std::istream &is, String &str);

	int refCount(); // 返回引用计数

	friend std::ostream &operator<<(std::ostream &os, const CharProxy &charPorxy);
private:
	char *malloc(const char *pstr = nullptr); // 为字符串申请空间
	void release(); // 释放字符串的空间
	void initRefCount(); // 初始化引用计数
	void increaseRefCount(); //增加引用计数
	void decreaseRefCount();<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值