模拟实现string类(c++)

#include<iostream>
#include<string>
using namespace std;
class STRING {
public:
STRING(const char* m = " ")//构造函数(赋值为空可以包含无参的情况)
:s(new char[strlen(m) + 1])
{
strcpy(s, m);
}
STRING(const STRING &m)//拷贝构造函数
{
s = new char[strlen(m.s) + 1];
strcpy(s, m.s);
}
~STRING()//析构函数
{
if (s != NULL)
delete s;
s = NULL;
}
STRING& operator=(STRING& m1)//赋值运算符重载
{
if (this != &m1)
{
if (s)
{
delete s;
}
s = new char[strlen(m1.s) + 1];
strcpy(s, m1.s);
}
return *this;
}
char& operator[](size_t  i)//下标运算符重载(size_t为一种记录大小的(无符号)"整型")
{
return s[i];
}
friend ostream& operator<<(ostream& output, STRING m);
private:
char* s;
};
ostream& operator<<(ostream& output, STRING m)
{
output << m.s;
return output;
}
void main()
{
STRING aa;
STRING ab = "hello!";
STRING ac = ab;
cout << ab << endl;
cout << ac << endl;
ab[1] = 'a';
cout << ab<< endl;

}

//拷贝构造函数使用引用类型是为了避免拷贝构造函数无限递归下去
/*使用参数列表赋值更有高效性,原因是少了一次调用默认构造函数的过程
(对于数据密集型的类来说,是非常高效的)*/

/*习惯使用const来表示变量不被改变的量,使用const在一定程度上可以提高程序的安全性和可靠性*/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值