#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;
};
模拟实现简单Mystring
最新推荐文章于 2023-09-12 08:54:41 发布