字符串封装
MyString.h
#pragma once
#include<iostream>
using namespace std;
class MyString
{
public:
friend ostream & operator<<(ostream &cout, const MyString &str);
friend istream &operator>>(istream &cin, MyString &str);
char &operator[](int index);
MyString &operator=(const MyString &str);
MyString operator+(const char *str);
MyString operator+(MyString &str);
bool operator==(MyString &str);
MyString();
MyString(const char *str);
MyString(const MyString & str);
~MyString();
private:
char *pString;
int m_Size;
};
ostream &operator<<(ostream &cout, const MyString &str);
ostream &operator>>(ostream &cin, MyString &str);
Mystring.cpp
#include "MyString.h"
ostream & operator<<(ostream &cout, const MyString &str)
{
cout << str.pString;
return cout;
}
std::istream & operator>>(istream &cin, MyString &str)
{
if (str.pString != NULL)
{
delete[]str.pString;
str.pString = NULL;
}
char buf[1024];
cin >> buf;
str.pString = new char[strlen(buf) + 1];
strcpy_s(str.pString, strlen(buf) + 1, buf);
str.m_Size = strlen(buf);
return cin;
}
char &MyString::operator[](int index)
{
return this->pString[index];
}
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_s(this->pString, strlen(str.pString) + 1, str.pString);
this->m_Size = strlen(str.pString) + 1;
return *this;
}
MyString MyString::operator+(const char *str)
{
int newsize = this->m_Size + strlen(str) + 1;
char *temp = new char[newsize];
memset(temp, 0, newsize);
strcat_s(temp,strlen(temp)+strlen(this->pString)+1,this->pString);
strcat_s(temp,strlen(temp)+strlen(str)+1, str);
MyString newString(temp);
delete[]temp;
return newString;
}
MyString MyString::operator+(MyString &str)
{
int newsize = this->m_Size + strlen(str.pString) + 1;
char *temp = new char[newsize];
memset(temp, 0, newsize);
strcat_s(temp, strlen(temp) + strlen(this->pString) + 1, this->pString);
strcat_s(temp, strlen(temp) + strlen(str.pString) + 1, str.pString);
MyString newString(temp);
delete[]temp;
return newString;
}
bool MyString::operator==(MyString &str)
{
return !(strcmp(this->pString, str.pString));
}
MyString::MyString()
{
;
}
MyString::MyString(const char *str)
{
this->pString = new char[strlen(str) + 1];
strcpy_s(this->pString, strlen(str) + 1, str);
this->m_Size = strlen(str);
}
MyString::MyString(const MyString & str)
{
this->pString = new char[strlen(str.pString)+1];
strcpy_s(this->pString, strlen(str.pString) + 1, str.pString);
this->m_Size = strlen(str.pString) + 1;
}
MyString::~MyString()
{
if (this->pString != NULL)
{
delete[]this->pString;
this->pString = NULL;
}
}
1.cpp
#include<iostream>
#include "MyString.h"
using namespace std;
void test01()
{
MyString p1 = "abc";
MyString p2 = "abd";
if (p1 == p2)
{
cout << "p1和p2相等" << endl;
}
else
{
cout << "p1和p2不相等" << endl;
}
}
int main()
{
test01();
system("pause");
return 0;
}