自定义String

// ShStringNew.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<iomanip>
using namespace std;
class SHString
{

public:
	SHString(const char* Str = "")
		:mStr(new char[strlen(Str) + 1])
	{
		strcpy(mStr, Str);
	}
	SHString(const SHString& Str)
		:mStr(new char[strlen(Str.mStr) + 1])
	{
		strcpy(mStr, Str.mStr);
	}
	SHString& operator=(const char* Str)
	{
		delete[] mStr;
		mStr = new char[strlen(Str) + 1];
		strcpy(mStr, Str);
		return *this;
	}
	SHString& operator=(const SHString& Str)
	{
		if (this != &Str)
		{
			delete[]mStr;
			mStr = new char[strlen(Str.mStr) + 1];
			strcpy(mStr, Str.mStr);
		}
		return *this;
	}
	~SHString()
	{
		delete[]mStr;
		mStr = NULL;
	}


public:
	char* mStr;
	friend ostream& operator<<(ostream& os, SHString& S);
	friend istream& operator >> (istream&, SHString& S);
	SHString operator+(const SHString &other);  //operator+

};

//因为模拟实现的string不是内置类型,所以要重载输出运算符,才能输出String类对象的内容
ostream& operator<<(ostream& os, SHString& Str)
{
	os << Str.mStr;
	return os;
}

istream &operator >> (istream &input, SHString &s)
{
	char temp[255]; //用于存储输入流
	input >> setw(255) >> temp;
	s = temp; //使用赋值运算符
	return input; //使用return可以支持连续使用>>运算符
}

inline SHString SHString::operator+(const SHString &other)
{
	SHString NewString;

	NewString.mStr = new char[strlen(mStr) + strlen(other.mStr) + 1];
	strcpy(NewString.mStr, mStr);
	strcat(NewString.mStr, other.mStr);

	return NewString;
}
int main()
{
	SHString Str1("abcdef");
	SHString Str2("ABCDEF");
	SHString Str3(Str1);
	SHString Str4,Str5,Str6;
	Str4 = Str1;
	char* v1 = "123";
	Str5 = v1;
	Str6 = Str4 + Str5;
	cout << "Str1->" << Str1 << endl;
	cout << "Str2->" << Str2 << endl;
	cout << "Str3->" << Str3 << endl;
	cout << "Str4->" << Str4 << endl;
	cout << "Str5->" << Str5 << endl;
	cout << "Str6->" << Str6 << endl;
    return 0;
}

  

原文地址:https://www.cnblogs.com/lsh123/p/7581600.html