您的位置:首页 > 编程语言 > C语言/C++

模拟实现string类(c++)

2017-07-02 18:09 323 查看
#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在一定程度上可以提高程序的安全性和可靠性*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: