简单String类功能实现

一般是要求实现构造函数、拷贝构造函数、赋值函数、析构函数这几个非常重要的部分。因为String里涉及动态内存的管理,默认的拷贝构造函数在运行时只会进行浅复制,即只复制内存区域的指针,会造成两个对象指向同一块内存区域的现象。如果一个对象销毁或改变了该内存区域,会造成另一个对象运行或者逻辑上出错。这时就要求程序员自己实现这些函数进行深复制,即不止复制指针,需要连同内存的内容一起复制。

具体代码如下:

/******************
Author : 杨永利
data   : 2020-06-28
*******************/
#include <string.h>
#include <assert.h>
#include <iostream>

using namespace std;

class String
{
public:
	String(const char *str = NULL);	//通用构造函数
	String(const String &str);		//拷贝构造函数(深赋值)
	~String();						//析构函数

	String operator+(const String &str) const;	//重载+
	String& operator=(const String &str);		//重载=
	String& operator+=(const String &str);		//重载+=
	bool operator==(const String &str) const;	//重载==
	char& operator[](int n) const{assert(n <= length - 1); return data[n]; }	//重载[](内联函数)

	size_t size() const{ return length; }		//长度接口(内联函数)
	const char* c_str() const{ return data; }	//数据接口(内联函数)

	friend istream& operator>>(istream &is, String &str);//输入
	friend ostream& operator<<(ostream &os, String &str);//输出

private:
	char *data;		//字符串
	size_t length;	//长度
};

String::String(const char *str)
{
	if(str == NULL)
	{
		length = 0;
		data = new char[1];
		*data = '\0';
	}else{
		length = strlen(str);
		data = new char[length + 1];
		strcpy(data, str);
	}
}

String::String(const String &str)
{
	length = str.size();
	data = new char[length + 1];
	strcpy(data, str.c_str());
}

String::~String()
{
	delete []data;
	length = 0;
}

String String::operator+(const String &str) const
{
	String newString;
	newString.length = length + str.size();
	newString.data = new char[newString.length + 1];
	strcpy(newString.data, data);
	strcat(newString.data, str.data);
	return newString;
}

String& String::operator=(const String &str)
{
	if(this == &str)
	{
		return *this;
	}
	
	delete []data;
	length = str.size();
	data = new char[length + 1];
	
	strcpy(data, str.c_str());
	
	return *this;
}

String& String::operator+=(const String &str)
{
	if(str.size() == 0)
	{
		return *this;
	}
	
	length += str.size();
	char *t_data = new char[length + 2];
	
	strcpy(t_data, data);
	strcat(t_data, str.c_str());
	
	delete []data;
	data = t_data;
	
	return *this;
}

bool String::operator==(const String &str) const
{
	if(length == str.size() && !strcmp(data, str.c_str()))
	{
		return true;
	}
	
	return false;
}

istream& operator >>(istream &is, String &str)
{
	char temp[1024];
	is >> temp;
	str.length = strlen(temp);
	str.data = new char[str.length + 1];
	strcpy(str.data, temp);
	
	return is;
}

ostream& operator<<(ostream &os, String &str)
{
	os << str.data;
	
	return os;
}

int main()
{
	String s;	
	cin >> s;	
	cout << s << ": " << s.size() << endl;

	char a[] = "Hello", b[] = "World!";
	String s1(a), s2(b);	
	cout << s1 << " + " << s2 << " = " << s1 + s2 << endl;

	String s3 = s1 + s2;
	if (s1 == s3)	cout << "First: s1 == s3" << endl;
	s1 += s2;
	if (true == (s1 == s3))	cout << "Second: s1 == s3" << endl;
	
	cout<<s1[3]<<endl;
	
	return 0;
}

运行结果如下:
自己实现C++String类_C/C