文档详情

自己动手编写string类.pdf

发布:2017-05-24约8.02千字共8页下载文档
文本预览下载声明
自己动手编写string 类 题记:人们对事物的恐惧往往源自不了解,如果你能把它写出来,还怕不会用 吗? 对于那些对C++标准库中的string 不甚了解的读者来说,这篇文章的名称 可能会引起一些混淆。标准库中的 string 并不是一个独立的类,而是 basic_string 模板类的一个特化版本: typedef basic_stringchar, char_traitschar, allocatorchar string; 我们今天要做的事情是,模仿标准库 string 的行为,编写一个属于自己的 简单的string 类。为了与标准库中的string 相区分,我们将自己编写的类命名 为MyString。 声明篇 数据成员方面我们需要一个char 型指针来保存字符串,还需要一个size_t 型变量来保存字符串的长度。显然,它们是应该被封装的,我们将它们的权限设 置为private。 class MyString {private: size_t strLength; char* p_str; }; 下面我们来声明成员函数,当然,还有一些非成员函数。 想一想我们定义一个 string 变量有哪几种方式,一般情况下,以下四种方 式比较常见: //调用默认构造函数 string s1; //将s2 初始化为s1 的一个副本 string s2(s1); or string s2=s1; //将s3 初始化为一个字符串字面值副本 string s3(hello); or string s3=hello; //将s4 初始化为字符a的n 个副本 string s4(n,a); 下面给出相应的声明: //构造函数 MyString(); MyString(const MyString); MyString(const char*); MyString(const size_t,const char); 类中存在指针数据成员,我们当然需要自己定义一个析构函数。 //析构函数 ~MyString(); 一些基本的属性。 size_t length();//字符串的长度 bool empty();//字符串是否为空 string 中有个c_str()成员函数,返回C 风格字符串的指针,我们也加上这 个函数。 const char* c_str();//返回C 风格字符串的指针 下面该写操作符了,我们知道,string 支持的操作符特别多,这些都是通 过操作符的重载实现的。 //读写操作符 friend ostream operator (ostream,const MyString); friend istream operator (istream,MyString); // ‘+’操作符 friend MyString operator+(const MyString,const MyString); // 比较操作符 friend bool operator==(const MyString,const MyString); friend bool operator!=(const MyString,const MyString); friend bool operator(const MyString,const MyString); friend bool operator=(const MyString,const MyString); friend bool operator(const MyString,const MyString); friend bool operator=(const MyString,const MyString); //下标操作符 char operator[] (const size_t); const char operator[] (const size_t)const; //赋值操作符 MyString operator=(const MyString); //+=操作符 MyString operator
显示全部
相似文档