模拟实现string

1.初始化成员列表高效在哪里

对类类型来说,用初始化列表少了一次调用默认构造函数的过程,这对于数据密集型的类来说,是非常高效的。

2.形参为const引用的好处

a.当实参的类型比较大时,复制开销很大,引用会“避免复制”。

b.“避免修改实参”,当使用引用时,如果调用者希望只使用实参并不修改实参,则const可以避免使用该引用修改实参。

3.使用&的好处

形参是对象的引用,是通过传地址的方法传递参数的,对函数形参的改变就是对实参的改变,如果函数的形参是对象,则是通过传值的方法传递参数的,函数体内对形参的修改无法传到函数体外。

4.模拟实现string

#include<iostream>
#include<string>
using namespace std;
class Mystring
{private:
char *_s;
public:
Mystring(const char *s=" "):_s(new char[strlen(s)+1)])
{
strcpy(_s,s);
}
Mystring(const Mystring &a):_s(new char[strlen(a._s)+1])
{
strcpy(_s,a._s);
}
~Mystring()
{
if(_s)
{
delete[]_s;
_s=NULL;
}
}
friend osteram& opreator<<(ostream &os,Mystring a);
Mystring& operator=(const Mystring a);
char& operator[](size_t i);
};
osteram& opreator<<(ostream &os,Mystring a)
{
os<<a._s;
return os;
}
Mystring& Mystring::operator=(const Mystring a)
{
if(this !=&a)
{
if(_s)
{_s=NULL;
}
_s=new char[strlen(a._s)+1];
strcpy(_s,a._s);
}
return *this;
}
char& Mystring::operator[](size_t i)
{
return _s[i];
}
int main()
{
Mystring arr;
Mystring brr;
Mystring crr="abcdefg";
arr=crr;
brr=crr;
cout<<arr<<endl;
cout<<brr<<endl;
arr[5]='h';
cout<<arr<<endl;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值