c++实现string类

来源:互联网 发布:淘宝企业店铺条件 编辑:程序博客网 时间:2024/06/10 01:03

简单实现String类(构造函数,复制构造函数,析构函数,赋值和输出运算符重载)

#define _CRT_SECURE_NO_WARNINGS#include <iostream>using namespace std;class MyString{public:    MyString(const char* s = "") :_s(new char[strlen(s) + 1])    {        strcpy(_s, s);    }    MyString(const MyString &s) :_s(new char[strlen(s._s) + 1])    {        strcpy(_s, s._s);    }    ~MyString()    {        if (_s)        {            delete[] _s;            _s = NULL;        }    }    MyString& operator =(MyString &s) {        if (s._s != NULL) {            delete[] _s;            _s = new char[strlen(s._s) + 1];            strcpy(_s, s._s);            _s[strlen(s._s)] = '\0';        }        return *this;    }    friend ostream& operator<< (ostream &, MyString&);private:    char* _s;};ostream& operator<<(ostream& os, MyString& str){    os << str._s;    return os;}int main(){    MyString arr;    MyString str = "hello";    MyString trr = str;    cout << arr << endl;    cout << str << endl;    cout << trr << endl;    system("pause");    return 0;}

1、使用初始化列表的好处:
(1)为初始化基类传递参数,使其能够有参初始化基类。
(2)提高组合类成员的初始化效率。因为初始化列表比把组合成员放在构造函数中初始化,省略了调用组合成员对象的赋值构造函数,同时也省略了因为显式调用组合成员的构造函数而生成的临时对象。
2、使用&的好处:
&不用将初始值进行拷贝,而是与初始值绑定在一起,提高了传递参数的效率 。
3、 const的作用:
http://www.cnblogs.com/xudong-bupt/p/3509567.html

原创粉丝点击