资源描述:
《c_c++语言程序设计笔试面试题22》由会员上传分享,免费在线阅读,更多相关内容在行业资料-天天文库。
1、下面是微软的两道笔试题....3.ImplementastringclassinC++withbasicfunctionalitylikecomparison,concatenation,input
andoutput.Pleasealsoprovidesometestcasesandusingscenarios(samplecodeofusingthis
class).PleasedonotuseMFC,STLandotherlibrariesinyourimplementation.我的实现方案如下,这道题真地对c++的主要特性都进行了较好地考察.String
2、.h:#ifndefSTRING_H#defineSTRING_H#includeusingnamespacestd;classString{public:String();String(intn,charc);String(constchar*source);String(constString&s);//String&operator=(char*s);String&operator=(constString&s);~String();char&operator[](inti){returna[i];}constchar&operator[
3、](inti)const{returna[i];}//对常量的索引.String&operator+=(constString&s);intlength();friendistream&operator>>(istream&is,String&s);//搞清为什么将>>设置为友元函数的原因.//friendbooloperator<(constString&left,constString&right);friendbooloperator>(constString&left,constString&right);//下面三个运算符都没必要设成友元
函数,这里是为
4、了简单.friendbooloperator==(constString&left,constString&right);friendbooloperator!=(constString&left,constString&right);private:char*a;intsize;};#endifString.cpp:#include"String.h"#include#includeString::String(){a=newchar[1];a[0]=' ';size=0;}String::String(intn,charc
5、){a=newchar[n+1];memset(a,c,n);a[n]=' ';size=n;}String::String(constchar*source){if(source==NULL){a=newchar[1];a[0]=' ';size=0;}else{size=strlen(source);a=newchar[size+1];strcpy(a,source);}}String::String(constString&s){size=strlen(s.a);//可以访问私有变量.a=newchar[size+1];//if(a==NULL)strc
6、py(a,s.a);}String&String::operator=(constString&s){if(this==&s)return*this;else{delete[]a;size=strlen(s.a);a=newchar[size+1];strcpy(a,s.a);return*this;}}String::~String(){delete[]a;//}String&String::operator+=(constString&s){intj=strlen(a);intsize=j+strlen(s.a);char*tmp=newchar[size+1
7、];strcpy(tmp,a);strcpy(tmp+j,s.a);delete[]a;a=tmp;return*this;}intString::length(){returnstrlen(a);}main.cpp:#include#include"String.h"usingnamespacestd;booloperator==(constString&left,constString&right){inta=strcmp(left.a,right.a);if(a==0)returntrue;elsereturnfalse;}boolope
8、rator