1.头文件部分
#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include<iostream>
#include<memory.h>
using namespace std;
class MyString
{
public:
//空参数构造函数
MyString();
//通过字符串常量创建的构造函数
MyString(const char * str);
//拷贝构造函数
MyString(const MyString & another);
~MyString();
//重载+运算符,模拟string类,返回的是匿名的MyString对象
MyString operator+(MyString & another);
//重载=运算符
MyString & operator=(MyString & another);
//重载[]运算符
char & operator[](int index);
//重载<<运算符
friend ostream & operator<<(ostream &os, MyString &s);
//重载>>运算符
friend istream & operator>>(istream &is, MyString &s);
//重载==运算符
bool operator==(MyString & another);
private:
//字符串的长度
int len;
//字符串指针
char *str;
};
2.函数定义部分
#include "MyString.h"
MyString::MyString()
{
this->len = 0;
this->str = NULL;
}
MyString::MyString(const char * str)
{
this->len = strlen(str);
this->str = new char[this->len + 1];
strcpy(this->str, str);
}
//拷贝构造函数
MyString::MyString(const MyString & another)
{
this->len = another.len;
this->str = new char[this->len + 1];
strcpy(this->str, another.str);
}
MyString::~MyString()
{
if (this->str != NULL) {
delete[] this->str;//删除数组用delete[] !!!!!!!!
this->str = NULL;
this->len = 0;
}
}
MyString MyString::operator+(MyString & another)
{
//创建一个临时的MyString 对象,用于存储返回的临时对象
MyString temp;//通过无参构造函数创建
temp.len = this->len + another.len;
temp.str = new char[temp.len + 1];
//先用msmset()函数格式化一下刚才开辟的内存空间,才能使用strcat
memset(temp.str,0,temp.len+1);
strcat(temp.str, this->str);
strcat(temp.str, another.str);
return temp;
}
MyString& MyString::operator=(MyString & another)
{
//防止自身复制
if (this->str == another.str) {
return *this;
}
//销毁自身之前对应的堆内存空间
if (this->str != NULL) {
delete[] this->str;//删除数组用delete[] !!!!!!!!
this->str = NULL;
this->len = 0;
}
//执行深拷贝
int len = another.len;
this->len = len;
this->str = new char[len + 1];
strcpy(this->str, another.str);
//返回自身的引用
return *this;
}
char & MyString::operator[](int index)
{
//返回的是某个MyString 对象中某个字符的引用,这样它能够成为左值
return this->str[index];
}
bool MyString::operator==(MyString & another)
{
//首先判断是不是自己
if (this->str == another.str) {
return true;
}
//其次判断个数是否相等,个数不等false
if (this->len != another.len) {
return false;
}
//最后就是通过[]操作符重载来判断每一个字符是否相等了
for (int i = 0; i < this->len; i++) {
if (this->str[i] != another.str[i]) {
return false;
}
}
return true;
}
ostream & operator<<(ostream &os, MyString &s) {
//返回的是ostream的引用
os << s.str;
return os;
}
istream & operator>>(istream & is, MyString & s)
{
// 正确的做法是先创建一个临时的字符数组,让is存入里面,再将里面的数据初入MyString对象s中
//或者新建立一个MyString 对象,通过空参数构造函数,str创建一个比较大的存储字符串的内存空间
//最后将临时对象通过=操作符重载拷贝给s
cout << "请输入字符串:" << endl;
MyString temp;
temp.str = new char[4097];//创建一个能存储4096个字符的字符串内存空间
is >> temp.str;
temp.len = strlen(temp.str);//获得输入字符串的有效字符个数
s = temp;//调用了=号操作符重载函数
return is;
}
本文详细介绍了一个自定义字符串类MyString的设计与实现过程,包括构造函数、析构函数、运算符重载等功能,并深入探讨了内存管理和字符串操作的具体实现。
223

被折叠的 条评论
为什么被折叠?



