模拟实现 string类

#include<iostream>
#include<string>
using namespace std;


class Mystring {
private:
	char *_s;
public:
	Mystring(const char *p = " "):_s(new char[strlen(p)+1])//const使*p的内容不被改变
	{ 
		strcpy(_s,p); }
	Mystring(const Mystring &p):_s ( new char[strlen(p._s) + 1])
	{
		
		strcpy(_s, p._s);
	}
	~Mystring()
	{
		if (_s)
			delete[]_s;_s = NULL;
	}
	friend ostream&operator<<(ostream &os, Mystring p);
	Mystring& operator = (const Mystring p);//返回值为引用,解决连等问题
	char& operator[](size_t i);
};
ostream& operator<<(ostream &os, Mystring p)
{
	os << p._s;
	return os;
}
Mystring&Mystring::operator=(const Mystring p)
{
	if (this != &p)
	{
		if(_s)
		{ 
			_s = NULL;
		}
		_s = new char[strlen(p._s) + 1];
		strcpy(_s, p._s);
	}
	return *this;
}
char&Mystring::operator[](size_t i)//size_t:无符号整型
{
	return  _s[i];
}
void main()
{
	Mystring ptr;
	Mystring trr;
	Mystring arr = "how are you!";
	ptr = arr;
	trr = arr;
	cout << arr << endl;
	cout << ptr << endl;
	trr[5]='e';
	cout << trr;
	cout << endl;

}

1.通过参数列表的形式给私有成员初始化,少了一次调用默认构造函数的过程。

2.函数的参数传递需要调用拷贝构造函数,所以拷贝构造函数中的参数传递需要调用拷贝构造函数,这样就会造成递归调用。按引用传递 则 传递的是地址,就不会出现这种问题

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值