#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *data;
int size;
public:
My_string():size(15)
{
data=new char [size];
data[0]='\0';
cout<<"My_string::无参构造"<<endl;
}
My_string(const char *str)
{
size=strlen(str);
this->data=new char[size];
strcpy(data,str);
cout<<"My_string::有参构造"<<endl;
}
~My_string()
{
cout<<"My_string::析构函数"<<endl;
delete data;
size=0;
}
//拷贝构造
My_string(const My_string &other):size(other.size)
{
this->data=new char[size];
strcpy(data,other.data);
cout<<"My_string::拷贝构造"<<endl;
}
//拷贝赋值
My_string & operator=(const My_string &other)
{
strcpy(data,other.data);
this->size=other.size;
cout<<"My_string::拷贝赋值"<<endl;
return *this;
}
void show()
{
cout<<data<<endl;
}
bool empty()
{
if(size==0)
{
return true;
}
else
{
return false;
}
}
//求长度
int sizes()
{
return size;
}
//at
char &at(int pos){
return data[pos];
}
//c风格转换
char *c_str(){
return data;
}
};
int main()
{
My_string s1;
s1.show();
My_string s2("hello");
s2.show();
My_string s3(s2);
s3.show();
My_string s4;
s4=s3;
s4.show();
cout<<s4.sizes()<<endl;
s4.at(3)='L';
cout<<s4.at(3)<<endl;
printf("%s\n",s4.c_str());
return 0;
}
结果