头文件string.h
#pragma once
//#ifndef MYSTRING_H_
//#define MYSTRING_H_
//#include <stddef.h>
#include <iostream>
using namespace std;
class MyString
{
public:
MyString(const char* str = NULL);
MyString(const MyString& another);
MyString& operator = (const MyString& another);
MyString operator + (const MyString& another);
bool operator > (const MyString& another);
bool operator < (const MyString& another);
bool operator == (const MyString& another);
char& operator[](int idx);
void dis();
~MyString(void);
private:
char* _str;
};
//#endif
cpp文件
#include "MyString.h"
// 默认构造器
MyString::MyString(const char* str)
{
if (NULL == str)
{
_str = new char[1];
*_str = '\0';
}
else
{
int len = strlen(str);
_str = new char[len + 1];
strcpy_s(_str, len + 1, str);
}
}
// 拷贝构造器
MyString::MyString(const MyString& another)
{
int len = strlen(another._str);
_str = new char[len + 1];
strcpy_s(_str, len + 1, another._str);
}
// 析构函数
MyString::~MyString()
{
delete[]_str;
}
// 赋值运算符重载
MyString& MyString::operator = (const MyString& another)
{
// 自赋值,出现错误
if (this == &another)
{
return *this;
}
// 先删除自己开辟的空间
delete[]_str;
int len = strlen(another._str);
this->_str = new char[len + 1];
strcpy_s(this->_str, len + 1, another._str);
return *this;
}
// 加法运算符重载
MyString MyString::operator + (const MyString& another)
{
int len = strlen(this->_str) + strlen(another._str);
MyString str;
delete[]str._str;
str._str = new char[len + 1];
memset(str._str, 0, len + 1);
int len1 = strlen(this->_str) + 1;
strcat_s(str._str, len1, this->_str);
// 源串长度 + 目标串长度 + 结束符
int len2 = strlen(this->_str) + strlen(another._str) + 1;
strcat_s(str._str, len2, another._str);
return str;
}
// ==关系运算符重载
bool MyString::operator==(const MyString& other)
{
if (strcmp(this->_str, other._str) == 0)
return true;
else
return false;
}
// >关系运算符重载
bool MyString::operator>(const MyString& other)
{
if (strcmp(this->_str, other._str) > 0)
return true;
else
return false;
}
// <运算符重载
bool MyString::operator<(const MyString& other)
{
if (strcmp(this->_str, other._str) < 0)
return true;
else
return false;
}
// []运算符重载
char& MyString::operator[](int idx)
{
return _str[idx];
}
// 打印函数
void MyString::dis()
{
using namespace std;
for (size_t i = 0; i < strlen(this->_str); i++)
{
cout << _str[i];
}
cout << endl;
}
测试文件
#include "MyString.h"
using namespace std;
void main()
{
// 验证默认构造函数
MyString str("Hello World");
str.dis();
// 验证赋值操作符
MyString str1 = str;
str1.dis();
MyString str1_1, str1_2, str1_3;
str1_1 = str1_2 = str1_3 = str;
str1_1.dis();
str1_2.dis();
str1_3.dis();
// 验证拷贝函数
MyString str2(str);
str2.dis();
// 验证连接函数
MyString str3("Hello China ");
str3 = str3 + str;
str3.dis();
// 验证关系运算符
MyString str4("abc");
MyString str5("bcd");
if (str4 < str5)
{
cout << "str4 < str5" << endl;
}
// 验证[]运算符
cout << str4[0] << str4[1] << str4[2] << endl;
system("Pause");
}