码迷,mamicode.com
首页 > 其他好文 > 详细

String类

时间:2016-04-27 19:06:57      阅读:175      评论:0      收藏:0      [点我收藏+]

标签:c++   string类

class String

{

public:

                String( const char *str);

                String( const String &other);

                ~String();

                 String &operator=(const String &other);


private:

                 char *data;

};


//构造函数

String::String(const char *str)

{

                 if (str == NULL)   //指针可能为空,要判断

                {

                                data = new char [1];

                                *data = ‘\0‘;

                }

                 else

                {

                                 int length = strlen(str );

                                data = new char [length + 1];

                                strcpy(data, str);

                }

}

//析构函数

String::~String()

{

                 delete data;

}

//拷贝构造函数

String::String(const String & other)

{

                 int length = strlen(other .data);

                data = new char [length + 1];

                strcpy(data, other.data);

}

//赋值函数

String &String ::operator=(const String & other)

{

                 if (this == &other)   //引用不可能为空,所以不用判断,注意不要错写为:if(*this==other)

                {

                                 return *this ;

                }

                 delete data; //释放原有的内存资源,以后没机会释放

                 int length = strlen(other .data);   //strlen不包含‘0’,strcpy包含‘0’一起复制

                data = new char [length + 1];

                strcpy(data, other.data);


                 return *this ;  //返回本对象的引用,为了实现像a=b=c这样的链式表达

}



时间问题,后期有需要补充的会陆续补充

String类

标签:c++   string类

原文地址:http://10921020.blog.51cto.com/10911020/1768266

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!