main.cpp
#include<iostream>
#include"MyString.h"
using namespace std;
int main()
{
String str1 = "aaa";
String str2 = "aaaa";
if (str1 == str2) {
cout << "str1==str2";
}
else
{
cout << "str1!=str2";
}
}
Mystring.cpp
#include"MyString.h"
String::String(const char* str)
{
//cout << "有参构造调用" << endl;
this->pString = new char[strlen(str) + 1];
strcpy(this->pString, str);
this->m_size = strlen(str);
}
String::String(const String& str)
{
this->pString = new char[strlen(str.pString) + 1];
strcpy(this->pString, str.pString);
this->m_size = str.m_size;
}
String::~String()
{
//cout << "析构函数调用" << endl;
if (this->pString != NULL) {
delete []this->pString;
this->pString = NULL;
}
}
String& String::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);
return *this;
}
String& String::operator=(const String & str)
{
if (this->pString != NULL) {
delete[]this->pString;
this->pString = NULL;
}
this->pString = new char[strlen(str.pString)+1];
strcpy(this->pString, str.pString);
return *this;
}
char& String::operator[](int index)
{
return this->pString[index];
}
String String::operator+(const char* str)
{
//计算返回的字符串开辟的大小
int newSize = this->m_size + strlen(str) + 1;
char* tmp = new char[newSize];
memset(tmp, 0, newSize);
//拼接字符串
strcat(tmp, this->pString);
strcat(tmp, str);
String newStr(tmp);
delete[] tmp;
return newStr;
}
//返回值是一个新的数据所以不用引用。
String String::operator+(const String& str)
{
int newSize = this->m_size + strlen(str.pString)+1;
char* tmp = new char[newSize];
memset(tmp, 0, newSize);
//拼接字符串
strcat(tmp, this->pString);
strcat(tmp, str.pString);
String newStr(tmp);
delete[]tmp;
return newStr;
}
bool String::operator==(const char* str)
{
if (strcmp(this->pString, str) == 0 && this->m_size == strlen(str)) {
return true;
}
return false;
}
bool String::operator==(const String& str)
{
if (strcmp(this->pString, str.pString) == 0 && this->m_size == str.m_size) {
return true;
}
return false;
}
ostream& operator<<(ostream& cout, String &str1)
{
cout << str1.pString;
return cout;
}
istream& operator>>(istream& cin, String& str1)
{
cin >> str1.pString;
return cin;
}
Mystring.h
#pragma once
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
using namespace std;
class String {
//重载<<运算符,全局函数
friend ostream& operator<<(ostream& cout, String& str1);
friend istream& operator>>(istream& cin, String& str1);
public:
String() {};
String(const char * str);
String(const String& str);
~String();
//重载等号运算符
String& operator=(const char* str);
String& operator=(const String& str);
//重载[]运算符
char& operator[](int index);
//重载+运算符
String operator+(const char *str);
String operator+(const String& str);
//重载==运算符
bool operator==(const char* str);
bool operator==(const String & str);
private:
char* pString;
int m_size;
};