欢迎来到天天文库
浏览记录
ID:15948490
大小:43.50 KB
页数:8页
时间:2018-08-06
《假设我们要开发一个string类,它可以方便地处理字符串数据》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、假设我们要开发一个String类,它可以方便地处理字符串数据。我们可以在类中声明一个数组,考虑到有时候字符串极长,我们可以把数组大小设为200,但一般的情况下又不需要这么多的空间,这样是浪费了内存。对了,我们可以使用new操作符,这样是十分灵活的,但在类中就会出现许多意想不到的问题,本文就是针对这一现象而写的。现在,我们先来开发一个Wrong类,从名称上看出,它是一个不完善的类。的确,我们要刻意地使它出现各种各样的问题,这样才好对症下药。好了,我们开始吧! Wrong.h:#ifndefWRONG_H_#defineWRONG_H_
2、classWrong{private:char*str;//存储数据intlen;//字符串长度public:Wrong(constchar*s);//构造函数Wrong();//默认构造函数~Wrong();//析构函数friendostream&operator<<(ostream&os,constWrong&st);};#endifWrong.cpp:#include<iostream>#include<cstring>#include"wrong.h"usingnamespacestd;Wrong::Wrong(constch
3、ar*s){len=strlen(s);str=newchar[len+1];strcpy(str,s);}//拷贝数据Wrong::Wrong(){len=0;str=newchar[len+1];str[0]=' ';}Wrong::~Wrong(){cout<<"这个字符串将被删除:"<<str<<'';//为了方便观察结果,特留此行代码。delete[]str;}ostream&operator<<(ostream&os,constWrong&st){os<<st.str;returnos;}test_right.cpp
4、:#include<iostream>#include<stdlib.h>#include"Wrong.h"usingnamespacestd;intmain(){Wrongtemp("天极网");cout<<temp<<'';system("PAUSE");return0;} 运行结果: 天极网 请按任意键继续... 大家可以看到,以上程序十分正确,而且也是十分有用的。可是,我们不能被表面现象所迷惑!下面,请大家用test_wrong.cpp文件替换test_right.cpp文件进行编译,看看结果。有的编译器可能就是根
5、本不能进行编译! test_wrong.cpp:#include<iostream>#include<stdlib.h>#include"Wrong.h"usingnamespacestd;voidshow_right(constWrong&);voidshow_wrong(constWrong);//注意,参数非引用,而是按值传递。intmain(){Wrongtest1("第一个范例。");Wrongtest2("第二个范例。");Wrongtest3("第三个范例。");Wrongtest4("第四个范例。");cout<<"
6、下面分别输入三个范例:";cout<<test1<<endl;cout<<test2<<endl;cout<<test3<<endl;Wrong*wrong1=newWrong(test1);cout<<*wrong1<<endl;deletewrong1;cout<<test1<<endl;//在Dev-cpp上没有任何反应。cout<<"使用正确的函数:"<<endl;show_right(test2);cout<<test2<<endl;cout<<"使用错误的函数:"<<endl;show_wrong(test2);cou
7、t<<test2<<endl;//这一段代码出现严重的错误!Wrongwrong2(test3);cout<<"wrong2:"<<wrong2<<endl;Wrongwrong3;wrong3=test4;cout<<"wrong3:"<<wrong3<<endl;cout<<"下面,程序结束,析构函数将被调用。"<<endl;return0;}voidshow_right(constWrong&a){cout<<a<<endl;}voidshow_wrong(constWronga){cout<<a<<endl;} 运行结果:
8、 下面分别输入三个范例: 第一个范例。 第二个范例。 第三个范例。 第一个范例。 这个字符串将被删除:第一个范例。 使用正确的函数: 第二个范例。 第二个范例。 使用错误的函数: 第二个范例。
此文档下载收益归作者所有