C++中字符串的實現

 

#pragma once
#include<string.h>
#include<iostream>

using namespace std;

class MyString
{
public:
	MyString();
	MyString(const char* string);
	MyString(const MyString& string);
	~MyString();
	size_t length();

	MyString operator+(const MyString& s);
	MyString operator+=(const MyString& s);
	MyString operator=(const MyString& s);
	char& operator[](int n);
	friend ostream& operator<<(ostream& out, MyString& s);
	friend istream& operator>>(istream& in, MyString& s);

private:
	char* str;
	/*int len;*/
};



MyString::MyString()
{
	str = nullptr;
}


MyString::MyString(const char* string)
{
	auto len = strlen(const_cast<char*>(string));
	this->str = new char[len+1];
	memcpy(this->str, string, len);	//深拷貝
	str[len] = '\0';
}

MyString::MyString(const MyString& string)
{
	memcpy(str, string.str, strlen(string.str)+1);	//深拷貝
	str[strlen(string.str)] = '\0';
};

inline MyString::~MyString()
{
	delete str;
}

inline size_t MyString::length()
{
	return strlen(str);
}

MyString MyString::operator+(const MyString& s)
{
	MyString r;
	auto len = strlen(s.str);;
	auto myl = strlen(this->str);
	r.str=new char[myl+len+1];
	memcpy(r.str, this->str, myl);
	memcpy(&(r.str[myl]), s.str, len);
	str[myl + len] = '\0';
	return r;
}

MyString MyString::operator+=(const MyString& s)
{
	auto len = strlen(s.str);;
	auto myl = strlen(this->str);
	this->str = new char[len+myl+1];
	memcpy(&(this->str[myl]), s.str, len);
	str[len + myl] = '\0';
	return *this;
}

MyString MyString::operator=(const MyString& s)
{
	delete str;
	auto len = strlen(s.str);
	this->str = new char[len+1];
	memcpy(this->str, s.str, len);
	str[len] = '\0';
	return *this;
}

char& MyString::operator[](int n)
{
	char& tmp = str[0];
	auto len = strlen(str);
	if (n >= len)
		tmp = str[len - 1];
	else if (n >= 0)
		tmp = str[n];
	return tmp;
}

ostream& operator<<(ostream& out, MyString& s)
{
	out << s.str;
	return out;
}

istream& operator>>(istream& in, MyString& s)
{
	in >> s.str;
	return in;
}




/********************************************************************
*Complier:VS2013
*Project:Overloaded Operator	重載運算符
*Author:Rise
*Examination:
1、

實現自己的MyString類,完成構造,析構,拷貝構造,+,+=,=,[],<<,>>,length的功能。
要求和string類的這些功能相似。
**********************************************************************/
#include<iostream>
#include<string>
#include"MyString.h"
using namespace std;

int main()
{
	/*cout << "hello world!\n";*/
	/*string a("hello");
	string b("world");
	cout << a << b << endl;
	cout << a << endl;*/
	MyString ma("hello");
	cout << ma ;
	return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章