String类的实现

来源:互联网 发布:mac系统开机密码忘了 编辑:程序博客网 时间:2024/04/29 00:38
#include <iostream>#include<string.h>using namespace std;class String{public:friend ostream& operator<<(ostream& os,const String& rhs);friend istream& operator>>(istream& is,String& rhs);String(const char* str=NULL);String(const String& other);String& operator=(const String& other);String& operator=(const char* str);bool operator!()const;char& operator[](unsigned int index);const char& operator[](unsigned int index)const;~String();friend String operator+(const String& s1,const String s2);String& operator+=(const String& other);private:char* str_;};String::~String(){delete[] str_;}String::String(const char* str){str_=new char[strlen(str)+1];strcpy(str_,str);}String::String(const String& other){str_=new char[strlen(other.str_)+1];strcpy(str_,other.str_);}String& String:: operator=(const String& other){if(this==&other)return *this;delete[] str_;str_=new char[strlen(other.str_)+1];strcpy(str_,other.str_);return *this;}String& String:: operator=(const char* str){delete[] str_;str_=new char[strlen(str)+1];strcpy(str_,str);return *this;}bool String::operator!()const {return strlen(str_)!=0;}char& String::operator[](unsigned int index){return const_cast<char&>(static_cast<const String&>(*this)[index]);}const char& String::operator[](unsigned int index)const{return str_[index];}String operator+(const String& s1,const String s2){String str=s1;str+=s2;return str;}String& String::operator+=(const String& other){int len=strlen(str_)+strlen(other.str_)+1;char* newstr=new char[len];strcpy(newstr,str_);strcat(newstr,other.str_);delete[] str_;str_=newstr;return *this;}ostream& operator<<(ostream& os,const String& str){os<<str.str_;return os;}istream& operator>>(istream& is,String& str){char tmp[1024];is>>tmp;str=tmp;return is;}int main(){String s1("abcdefg");char ch=s1[2];cout<<ch<<endl;const String s2("xyzabc");ch=s2[2];cout<<s2<<endl;String s3="xxx";String s4="yyy";String s5=s3+s4;cout<<s5<<endl;String s6="aaa"+s3+"abcd"+"xxxx";cout<<s6<<endl;s3+=s4;cout<<s3<<endl;String s7;cin>>s7;cout<<s7<<endl;String s8;bool notempty;notempty=!s4;cout<<notempty<<endl;return 0;}

0 0
原创粉丝点击