代码:
#include <iostream>
#include <cstring>
using namespace std;
class My_string
{
private:
char *cstr;
int len;
public:
My_string() //无参构造
{
cstr=new char{};
len=0;
}
My_string(const char *str) //有参构造
{
len=strlen(str);
cstr=new char[len];
strcpy(cstr,str);
}
My_string(const My_string &other) //拷贝构造
{
len=other.len;
cstr=new char[len];
strcpy(cstr,other.cstr);
}
~My_string() //析构函数
{
delete cstr;
}
bool empty() //判断是否为空
{
if(len==0)
return true;
return false;
}
int size()//返回字符串的长度
{
return len;
}
char &at(int index) //
{
return cstr[index];
}
char* c_str() //转化为C风格字符串
{
return cstr;
}
void show()
{
cout<<"字符串:"<<cstr<<endl;
cout<<"长度:"<<len<<endl;
}
};
int main()
{
My_string s;
s.show();
if(s.empty())
{
cout<<"s为空"<<endl;
}
else
{
cout<<"s不为空"<<endl;
}
cout<<"**********************"<<endl;
My_string s1("jinghao");
s1.show();
if(s1.empty())
{
cout<<"s1为空"<<endl;
}
else
{
cout<<"s1不为空"<<endl;
}
s1.at(0)='J';
cout<<s1.c_str()<<endl;
cout<<"**********************"<<endl;
My_string s2(s1);
s2.show();
if(s2.empty())
{
cout<<"s2为空"<<endl;
}
else
{
cout<<"s2不为空"<<endl;
}
return 0;
}
代码运行: