39.1 myString.h
#define _CRT_SECURE_NO_WARNINGS
#pragma once
#include
using namespace std;
class MyString
{ //左移运算符重载 友元
friend ostream& operator< //右移运算符重载 友元
friend istream& operator>>(istream & cin, MyString & str);
public:
MyString(char * str); //有参构造
MyString(const MyString & str); //拷贝构造
char& operator[](int pos); // 重载 []运算符 // 按位置获得字符
MyString& operator=( const char * str); // 重载 = 运算符 // 字符串赋值
MyString& operator=(const MyString & str);
MyString operator+(const char * str); // 重载 +运算符 // 字符串拼接
MyString operator+(const MyString & str);
bool operator==(const char * str); //重载 == 运算符
bool operator==(const MyString & str);
~MyString(); //析构函数
private:
char * pString; // 指向堆区的字符串数组的指针
int m_Size; // 字符串长度
};
39.2 myString.cpp
#include "myString.h"
char& MyString::operator[](int pos)
{
return this->pString[pos];
}
MyString& MyString::operator=(const char * str)
{
if (this->pString != NULL) // 先判断 原理堆区是否有内容 ,如果有, 先释放
{
delete [] this->pString;
this->pString = NULL;
}
this->pString = new char[strlen(str) + 1]; // 开辟空间,赋值,更新类成员
strcpy(this->pString, str);
this->m_Size = strlen(str);
return *this;
}
MyString& MyString::operator=(const MyString & str)
{
if (this->pString != NULL)
{
delete[] this->pString;
this->pString = NULL;
}
this->pString = new char[strlen(str.pString) + 1];
strcpy(this->pString, str.pString);
this->m_Size = strlen(str.pString);
return *this;
}---------------------------------------------------------------------------------------------------
MyString MyString::operator+(const char * str)
{
//str1 = "abc"; str2 = "def" str4 = "abcdef";
//计算开辟多少空间
int newSize = this->m_Size + strlen(str) + 1;
char * temp = new char[newSize];
memset(temp, 0, newSize);
strcat(temp, this->pString); //字符串拼接
strcat(temp, str);
MyString newString(temp); // newString 调用拷贝构造
delete[] temp;
return newString;
}
MyString MyString::operator+(const MyString & str)
{
//计算开辟多少空间
int newSize = this->m_Size + strlen(str.pString) + 1;
char * temp = new char[newSize];
memset(temp, 0, newSize);
//字符串拼接
strcat(temp, this->pString);
strcat(temp, str.pString);
MyString newString(temp);
delete[] temp;
return newString;
}---------------------------------------------------------------------------------------------------
bool MyString::operator==(const char * str)
{
return strcmp(this->pString, str) == 0;
}
bool MyString::operator==(const MyString & str)
{
return strcmp(this->pString, str.pString) == 0;
}---------------------------------------------------------------------------------------------------
MyString::~MyString()
{
if (this->pString != NULL)
{
delete[] this->pString;
this->pString = NULL;
}
}