模拟实现简单Mystring

#pragma once
#include <iostream>
#include <stdio.h>
#include <assert.h>
using namespace std;
class MyString
{
	//############################################################
                   //传统写法
	//############################################################
public:
	MyString(char* str)
		:_str( new char[strlen(str)+1])//必须开辟新空间,为‘\0’开辟一个字节
	{
		assert(str);
		for (size_t i = 0; i <= strlen(str); i++)
		{
			_str[i] = str[i];
		}
		//strcpy(_str, str);  
	}
	MyString(const MyString& s) 
		:_str(new char[strlen(s._str)+1])//传引用,少一层拷贝
	{
		for (size_t i = 0; i <= strlen(s._str); i++)
		{
			_str[i] = _str[i];
		}
		//strcpy(_str, s._str);  
		
	}
	
	MyString& operator=(const MyString& s)
	{
		if (this != &s)
		{
			delete[]_str;
			_str = new char[strlen(s._str) + 1];
			strcpy(_str, s._str);     
			//首先释放空间,因为两个字符串的内存可能不               同,导致溢出或泄露    //开辟与要赋值的字符串相同的空间//赋值

		}
		return *this;
	}
	//有返回值 并引用,支持连续赋值,
    //还有const修饰,防止字符串被改变
     //传引用,提高效率(少一层拷贝构造)

	//############################################################
	                       //现代写法
	//############################################################
	MyString(const MyString& s)
		:_str(NULL)//传引用,少一层拷贝
	{
		MyString temp(s._str);
		swap(_str, temp._str);

	}

	MyString& operator=(MyString s)//拷贝构造s
	{
		if (this != &s)
		{
			swap(_str, s._str);
		}
		return *this;
	}
	MyString& operator=(const MyString& s)//拷贝构造s
	{
		if (this != &s)
		{
			MyString temp(s._str);
			swap(_str, temp._str);
		}
		return *this;
	}

	//####################################################
	char& operator[](const size_t num)
	{
		assert(num<strlen(_str));
		return _str[num];

	}
	bool operator>(const MyString&s)  //s1="hello"  s2="world"
	{
		assert(&s);
		const char* str1 = _str;
		const char* str2 = s._str;
		while (*str1 && *str2)
		{
			if (*str1 > *str2)
				return true;
			else if (*str1 < *str2)
				return false;
			else
			{
				str1++;
				str2++;
			}
		}
		if (*str1)
			return true;
		else
			return false;

	}
	bool operator==(const MyString&s)  //s1="hello"  s2="world"
	{
		assert(&s);
		const char* str1 = _str;
		const char* str2 = s._str;
		while (*str1 && *str2)
		{
			if (*str1 != *str2)
				return false;
			else
			{
				str1++;
				str2++;
			}
		}
		if (*str1 =='\0' && *str2=='\0')
			return true;
		else
			return false;

	}

	~MyString()
	{
		delete[]_str;
		_str = NULL;//防止野指针,不指空也无所谓,已经被析构
	}
private:
	char* _str;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值