一个简单的string类实现

#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企业版
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值