
代码
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
// 无参构造
my_string(){}
// 有参构造
my_string(char *s)
{
len=strlen(s);
//str=new char[len];
str=new char[len];
// memset(str,0,sizeof(str));
//strcpy(str,s);
str=s;
}
// 拷贝构造
my_string(my_string& O)
{
len=O.len;
str=O.str;
}
// 拷贝赋值
my_string& operator =(const my_string &R)//拷贝赋值
{
if (this != &R)
{
this->str=R.str;
this->len=R.len;
}
return *this;
}
bool my_empty()
{
if(len==0)
return true;
else
return false;
}
int my_size()
{
return len;
}
char *my_str()
{
return str;
}
void display()
{
//cout<<my_str()<<'\t'<<len<<endl;
cout<<my_str()<<'\t'<<"len:"<<len<<'\t';
}
};
int main()
{
//char s="das";
my_string s1("wangwu");
my_string s2(s1);
my_string s3("lisi");
s3=s2;
s1.display();
if(s1.my_empty())
cout<<"empty"<<endl;
else
cout<<"not empty"<<endl;
s2.display();
if(s2.my_empty())
cout<<"empty"<<endl;
else
cout<<"not empty"<<endl;
s3.display();
if(s3.my_empty())
cout<<"empty"<<endl;
else
cout<<"not empty"<<endl;
my_string s4("");
s4.display();
if(s4.my_empty())
cout<<"empty"<<endl;
else
cout<<"not empty"<<endl;
return 0;
}
运行结果
