代码功能:
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *data;
int len;
public:
My_string(const char *str=NULL)
{
if(str){ //有参构造
len=strlen(str);
data=new char[strlen(str)+1];
strcpy(data,str);
}else{ //无参构造
data=new char('\0');
len=0;
}
}
My_string(const My_string &other):len(other.len)//拷贝构造
{
data=new char[other.len+1];
strcpy(data,other.data);
}
My_string& operator=(const My_string &other)//拷贝赋值
{
if(this!=&other){
data=new char[other.len+1];
strcpy(data,other.data);
len=other.len;
}
return *this;
}
~My_string() //析构函数
{
delete []data;
cout<<"析构函数"<< " 析构地址为:"<< this <<endl;
}
bool empty() //判断是否为空
{
if(len==0)
{
return 0;
}
else
{
return 1;
}
}
int size() //返回字符串的长度
{
return len;
}
char &at(int index) //定位函数
{
if(index<0 || index >= len)
{
cout<<"定位错误!"<<endl;
}
return *(data+index);
}
char* c_str() //转化为C风格字符串
{
return data;
}
void show()
{
cout<<"cstr = "<<data<<endl;
cout<<"len = "<<len<<endl;
}
};
void show(My_string s)
{
cout<<"**************************"<<endl;
cout<<"字符串长度为>>>"<<s.size()<<endl;
cout<<"字符串为>>>"<<s.c_str()<<endl;
}
int main()
{
My_string s = "good time";
show(s);
My_string s1 = "hello world";
show(s1);
My_string s2 = "你好,世界!";
show(s2);
return 0;
}