- 工具VS2017
- MyString.h
#pragma once
#include<iostream>
using namespace std;
class MyString
{
friend ostream & operator<<(ostream &os, const MyString& s);
friend istream & operator>>(istream &is, MyString& s);
public:
MyString();
//MyString(int len);// 创建一个长度为len 的string 对象
MyString(const char *str); //有参构造
MyString(const MyString &another); //拷贝构造
~MyString();
//重载操作符[] << >> = + == !=
char &operator[](int index);
MyString& operator=(const MyString & another);
MyString operator+(const MyString & another);
private:
int len;
char *str;
};
- MyString.cpp
#define _CRT_SECURE_NO_WARNINGS
#include "MyString.h"
#include<iostream>
using namespace std;
MyString::MyString()
{
this->len = 0;
this->str = NULL; //和‘\0’等价的
}
MyString::MyString(const char *str)
{
if (str == NULL)
{
this->len = 0;
this->str = new char[0 + 1];
strcpy(this->str, "");
}
else
{
int len = strlen(str);
this->len = len;
this->str = new char[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)
{
cout << this->str << "执行了析构函数" << endl;
delete this->str;
this->str = NULL;
this->len = 0;
}
}
char& MyString::operator[](int index)
{
return this->str[index];
}
MyString& MyString::operator=(const MyString & another)
{
//1.检查是否为自身
if (this == &another)
{
return *this;
}
//2.清空原垃圾
if (this->str != NULL)
{
delete[] this->str;
this->str = NULL;
this->len = 0;
}
//3.深拷贝
this->len = another.len;
this->str = new char[this->len + 1];
strcpy(this->str, another.str);
return *this;
}
MyString MyString::operator+(const MyString & another)
{
MyString temp;
int len = this->len + another.len;
temp.len = len;
temp.str = new char[len + 1];
//memset(temp.str, 0, len + 1);
strcpy(temp.str, this->str);
strcat(temp.str, another.str);
return temp;
}
ostream & operator<<(ostream &os, const MyString& s)
{
os << s.str<< endl;
return os;
}
istream & operator>>(istream &is, MyString& s)
{
//1.将s之前的字符串释放掉
if (s.str != NULL)
{
delete[] s.str;
s.str = NULL;
s.len = 0;
}
//2.通过cin添加新的字符串
char temp_str[4096] = { 0 };
cin >> temp_str;
int len = strlen(temp_str);
s.len = len;
s.str = new char[len + 1];
strcpy(s.str, temp_str);
return is;
}
- main.cpp
#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <string>
#include "MyString.h"
using namespace std;
int main(void)
{
//string s1;
MyString s1("abc");
MyString s2("123");
MyString s3 = "456";
MyString s4("abcd");
MyString temp = s3 + s4;
s4 = s1 + s2 + (s3 + s4);
cout << s4 << endl;
cout << s1 + s2;
cout << s1 << endl;
cout << s2 << endl;
cout << temp << endl;
cin >> s4;
cout << s4 << endl;
//cout << s1 + s2 << endl;
cout << s1 << endl;
cout << s2 << endl;
s1[1] = 'x';
cout << s1 << endl;
s1 = s3;
cout << s1 << endl;
return 0;
}
5.总结
通过自己编写String类,来了解C++中string类的功能。