13.3 本章实例
在前面的章节中,字符串总是用"char *"来表示,串的处理函数和串的表示是分离的。本节将定义一个字符串类,将串的表示和处理函数封装在一起。
【实例13-1】 自定义的string类。
- class string
- {
- int length; //串长
- char * contents; //串的内容
- public:
- string(char *s); //构造函数,带参数
- ~string();
- void show();
- };
- string::string(char *s)
- {
- length=strlen(s); //计算串长
- contents=new char [length+1]; //申请内存
- strcpy(contents,s); //串赋值
- }
- string::~string()
- {
- delete[] contents; //释放串的空间
- length=0; //初始化串长度
- }
- string::show()
- {
- cout<<"string is\""<<contents<<"\".The length is "<<length<<"."<<endl;
- }
- void main()
- {
- string s1("the first string");
- s1.show();
- string s2("the second string");
- s2.show();
- }
程序运行结果如下:
分析:该字符串类将串的实现和处理封装在一起,构造函数带有参数。因此,创建字符串对象时必须带参数。由于串的长度是未知的,所以在构造函数中,根据串的实际长度动态申请内存空间。当退出时,一定要在析构函数中将申请的空间释放。否则,这片动态申请的内存空间将不能再被使用。
- string is "the first string". The length is 16.
- string is "the second string". The length is 17.
【责任编辑:云霞 TEL:(010)68476606】
| 回书目 上一节 下一节 |