#ifndef _MY_STRING_
#define _My_STRING_
class MyString
{
public:
MyString();
MyString(const char* buf);//带参数构造
MyString(const MyString& other);//拷贝构造
~MyString();//析构
int Len()const;//长度
char* c_str()const;//字符串
MyString operator+(const MyString& other);//重构“+”,用于字符串拼接;
MyString& operator=(const MyString& other);//重构“=”,用于字符串赋值;
bool operator==(const MyString& other);//重构“==”,判断字符串相等
char* data; //字符串
int data_len;//长度
};
#endif
#include "stdafx.h"
#include "MyString.h"
#include <iostream>
using namespace std;
MyString::MyString()
{
data_len = 0;
data = nullptr;
}
MyString::MyString(const char* buf)
{
if (buf == nullptr)
{
data_len = 0;
data = new char[1];
strcpy(data, "");
}
else
{
data_len = strlen(buf);//获得长度
data = new char[data_len + 1];//申请内存
strcpy(data, buf);//拷贝数据
}
}
MyString::MyString(const MyString& other)
{
data_len = strlen(other.data);//获得长度
data = new char[data_len + 1];//申请内存
strcpy(data, other.data);//拷贝数据
}
MyString::~MyString()
{
data_len = 0;
if (data != nullptr)
{
delete[]data;
data = nullptr;
}
}
int MyString::Len() const
{
return data_len;
}
char* MyString::c_str() const
{
return data;
}
MyString MyString::operator+(const MyString& other)
{
if (other.data == nullptr)
{
return *this;
}
else if (this->data == nullptr)
{
data_len = strlen(other.data);//获得长度
data = new char[data_len + 1];//申请内存
strcpy(data, other.data);//拷贝数据
return *this;
}
MyString Temp;
Temp.data_len = this->data_len + other.data_len;
Temp.data = new char[Temp.data_len + 1];
strcpy(Temp.data, this->data);
strcat(Temp.data, other.data);
return Temp;
}
MyString& MyString::operator=(const MyString& other)
{
if (other.data == nullptr)
{
return *this;
}
else if (&other == this)
{
return *this;
}
delete[] data;
data = nullptr;
data_len = other.data_len;
data = new char[other.data_len + 1];
strcpy(data, other.data);
return *this;
}
bool MyString::operator==(const MyString& other)
{
if (this->data_len != other.data_len)
{
return false;
}
else
{
return strcmp(this->data, other.data) ? false : true;
}
}
// MyString.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "MyString.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
MyString test_1("haha_1");
cout << test_1.c_str() << endl;
MyString test_2(test_1);
cout << test_2.c_str() << endl;
MyString test_3 = test_1 + test_2;
cout << test_3.c_str() << endl;
MyString test_4;
test_4 = test_3;
cout << test_4.c_str() << endl;
if (test_1 == test_2)
{
cout << "same_char"<< endl;
}
else
{
cout << "not_char" << endl;
}
char a;
a = getchar();
return 0;
}