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】