C++ 重载赋值运算符
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;
}
//如果返回值和参数都是对象而不是引用,那么一定记得要先定义拷贝构造函数,而且该拷贝构造内部完成的是深拷贝
my_string operator=(my_string s)
{
if(this->p)delete[]p;
if(s.p){
p=new char[s.size()+1];
strcpy(this->p,s.p);
}else{
this->p = nullptr;
}
return *this;
}
};
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";
//s3 = (s1=s2);
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;
}