模拟实现 string类

来源:互联网 发布:d3.js力导向拖拽 编辑:程序博客网 时间:2024/05/22 14:50
#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.函数的参数传递需要调用拷贝构造函数,所以拷贝构造函数中的参数传递需要调用拷贝构造函数,这样就会造成递归调用。按引用传递 则 传递的是地址,就不会出现这种问题