#include <iostream>
#include <cstdio>
#include <stdio.h>
#include <cstdlib>
#include <stdlib.h>
#include <cstring>
using namespace std;
class Mstring
{
public:
Mstring()
{
str=nullptr;
len=0;
cout<<"无参构造函数"<<endl;
}
Mstring(const char* const s)
{
len=strlen(s);
str=new char[len+1];
strcpy(str,s);
cout<<"有参构造函数"<<endl;
}
~Mstring()
{
if(str != nullptr)
{
delete []str;
str=nullptr;
}
cout<<this<<endl;
cout<<"析构函数"<<endl;
}
/* Mstring(Mstring &other)
{
len=other.len;
str=new char[len+1];
cout<<"浅拷贝构造函数"<<endl;
}
*/ Mstring(const Mstring &other)
{
len=other.len;
str=new char[len+1];
strcpy(str,other.str);
cout<<"深拷贝构造函数"<<endl;
}
//赋值拷贝函数
Mstring& operator=(const Mstring &other) //传引用&
{
if(&other != this)//如果自己赋值给自己(判断不等于自己,进行赋值)
{
len=other.len;
if(nullptr != str) //防止泄露,要判断是否有这个空间
{
delete []str;
str=nullptr;
}
str=new char[len+1];
strcpy(str,other.str);
}
cout<<"赋值拷贝函数"<<endl;
return *this;
}
//data()
char* data()
{
return str;
}
//size()
int size()
{
return len;
}
//empty()
bool empty()
{
return 0==len;
}
//at()
char& at(int index)
{
if(index<0 || index>=len)
{
cout<<index<<endl;
return str[0];
}
return str[index];
}
void show()
{
cout<<"len="<<len<<endl;
cout<<"str="<<str<<endl;
}
private:
int len;
char* str;
};
int main(int argc, const char *argv[])
{
Mstring s1="hello world";
s1.show();
return 0;
}