C++ string类简单实现

来源:互联网 发布:sql删除表中的重复数据 编辑:程序博客网 时间:2024/06/05 18:46
#include<iostream>#include<cstring>using namespace std;class MyString{friend ostream &operator<<( ostream &, const MyString & );public:MyString(const char *s);MyString( );MyString(const MyString &);~MyString(); MyString &operator +=(const MyString &); MyString operator +(const MyString &);MyString &operator = (const MyString &right);MyString &operator = (const char *);MyString &operator =(int );char &operator [](int subscript) ;    int getlength();     char *str; int length;};ostream & operator<<( ostream &os, const MyString &s ){  os << s.str;  return os;} MyString::MyString() :length(0) { cout<<"Default constructtion is called:"<<endl;      str = new char[1];      str[0]='\0'; }MyString::MyString(const char *s):length(strlen(s)){   cout<<"construct function is called:"<<endl;  str=new char[length+1];  strcpy(str,s); }MyString::~MyString(){ cout<<"Desconstruction is called:"<<endl;  delete []str;  str=NULL;}MyString::MyString(const MyString ©){  length=copy.length;  strcpy(str,copy.str);  }MyString & MyString::operator =(const MyString &right){if(this==&right)return *this;else{ delete []str;  str = new char[strlen(right.str)+1];        length=right.length;      strcpy(str,right.str);      return *this;}} MyString &MyString::operator +=(const MyString &right){ int newlength = length+right.length;  char *p = new char[newlength+1];  strcpy(p,str);  strcat(p,right.str);  delete [] str;    strcpy(str,p);  length=newlength;  delete [] p;  p=NULL;    cout<<"+= is be called!"<<endl;  return *this;} MyString & MyString::operator =(const char *s){ char *p = new char[strlen(s)+1];  strcpy(p,s);  delete [] str;  strcpy(str,p);  length=strlen(s);    return *this;} MyString MyString::operator +(const MyString &right){MyString p;delete p.str;p.str = new char[strlen(str)+strlen(right.str)+1];p.length=length+right.length;strcpy(p.str,str);strcat(p.str,right.str);    return p;}MyString & MyString::operator =(int num){ char a[30]; itoa(num,a,10); strcpy(str,a); length=strlen(a); return *this;}char & MyString::operator [](int subscript){  if(subscript > 0 || subscript < strlen(str))  return str[subscript-1];  else  {  cout<<"str:"<<subscript<<"out of range..."<<endl;    }}int main(){  MyString s("xupeng");  MyString p("xjw");  cout<<s.str<<endl;  cout<<s[3]<<endl;  cout<<p.str<<endl;    cout<<s+p<<endl;  cout<<p.str<<endl;    return 0;}

总结:

1、代码风格需要改善。

2、内存管理不了解。

3、VC++ 和 Dev-C++ 有差异。

原创粉丝点击