现在的位置: 首页 > 综合 > 正文

一个简单的string类实现

2018年10月18日 ⁄ 综合 ⁄ 共 1362字 ⁄ 字号 评论关闭
#include <iostream>
using namespace std;
class MyString
{
public:
	MyString(char *ptr=NULL);
	~MyString();
	MyString(const MyString& other);
	MyString& operator=(const MyString& other);
	friend ostream& operator<<(ostream& out, MyString &str)
	{
		if (str.m_data != NULL)
			out << str.m_data;
		return out;
	}
	friend istream& operator>>(istream& in, MyString &str)
	{
		str.m_data = new char[1024];	//当申请空间存放不下输入的字符串,就会越界
						//解决办法:用循环来读输入流中字符串,动态
						//分配成员m_data的大小或者用栈来实现字符串的储存
		in >> str.m_data;

		return in;
	}

private:
	char* m_data;
};

MyString::MyString(char *ptr):m_data(ptr)
{
	if (ptr == NULL)
	{
		m_data = new char[1];
		*m_data = '\0';
	}
	else
	{
		int nLen = strlen(ptr);
		m_data = new char[nLen+1];
		strcpy(m_data, ptr);
	}
}

MyString::~MyString()
{
	delete m_data;
}

MyString::MyString(const MyString& other)
{
	if (other.m_data != NULL)
	{
		int nLen = strlen(other.m_data);
		m_data = new char[nLen+1];
		strcpy(m_data, other.m_data);	
	}
}

MyString& MyString::operator=(const MyString& other)
{
	if (this == &other)	//是否自赋值
		return *this;
	delete []m_data;
	int nLen = strlen(other.m_data);
	m_data = new char[nLen+1];
	strcpy(m_data, other.m_data);

	return *this;
}

int main()
{
	MyString str("Hello");
	cout << str << endl;
	MyString str2;
	cout << str2 << endl;	//执行NULL分支字符串为空
	cout << "---------------------------" << endl;
	MyString str3;
	cin >> str3;	//输入字符串,长度小于1024
	cout << str3 << endl;
	cout << "---------------------------" << endl;
	MyString str4("Hello");
	cout << str4 << endl;
	MyString str5;
	str5 = str4;
	cout << str5 << endl;
	MyString str6(str4);
	cout << str6 << endl;

	return 0;
}

环境:WindowsXP+VC6.0企业版

抱歉!评论已关闭.