1 中括号重载.cpp
#include<iostream>
#include<string.h>
using namespace std;
class my_string{
char* p=nullptr;
public:
my_string(){}
my_string(const char* s){
if(s){
p = new char[strlen(s)+1];
strcpy(p,s);
}
}
my_string( const my_string& ms){
if(ms.p){
if(p)delete []p;
p = new char[ms.size()+1];
strcpy(p,ms.p);
}
}
~my_string(){
if(p)delete [] p;
}
friend ostream &operator<<(ostream&cout,my_string &s);
char & operator[](int pos)
{
return p[pos];
}
int size()const{return strlen(p);}
my_string operator+(my_string s)
{
my_string tmp;
tmp.p= new char[this->size()+s.size()+1];
strcpy(tmp.p,this->p);
strcat(tmp.p,s.p);
return tmp;
}
my_string operator+(const char* s)
{
my_string tmp;
tmp.p= new char[this->size()+strlen(s)+1];
strcpy(tmp.p,this->p);
strcat(tmp.p,s);
return tmp;
}
};
ostream &operator<<(ostream&cout,my_string &s)
{
cout<<s.p;
return cout;
}
int main()
{
my_string s="123";
my_string s1="abc";
my_string s2 =s+s1;//s2(s+s1);
// cout<<s2<<endl;//123abc
// my_string s3 = s1 + "mmm";
//'a',"123" =const char*
my_string s3 ;
//此处会出现double free,因为此处的=是赋值运算,做的是浅拷贝
s3= s1 + "mmm";
cout<<s3<<endl;//123abc
//s3 = s1+(s+s2);
// s[0] = 'a';
// cout<<s<<endl;
// cout<<s[0]<<endl;
// cout<<s<<endl;
// cout<<sizeof(s)<<endl;
return 0;
}