/*class my_string
{
private:
char *str;
int len;
publuc:
//无参构造
//有参构造
//拷贝构造
//拷贝赋值
//bool my_empty() 判空
//int my_size() 求长度
//char *my_str() 转化为c风格字符串
}
要求:前四个必须实现,后三个尽力而为*/
#include <iostream>
#include<string.h>
using namespace std;
class my_string
{
public:
//无参构造
my_string()
{
str=NULL;
len=0;
}
//有参构造
my_string(int l,char s)
{
this->len=l;
this->str=new char[len+1];
for(int i=0;i<len;i++)
{
(this->str)[i]=s;
}
}
//有参构造
my_string(char *str)
{
int i=0;
char *p=str;
while(1)
{
if(*(p+i)=='\0')
break;
i++;
}
this->str=new char[i+1];
for(int j=0;j<i+1;j++)
{
(this->str)[j]=p[j];
}
this->len=i;
}
//拷贝构造
my_string(const my_string&O):str(new char (*(O.str))),len(O.len){}
//拷贝赋值
my_string &operator=(const my_string &O)
{
if(&O!=this)
{
if(this->str!=NULL)
{
delete this->str;
this->str=NULL;
}
this->str=new char (*(O.str));
this->len=O.len;
}
}
//拷贝赋值
my_string &operator=(char *str)
{
int i=0;
char *p=str;
while(1)
{
if(*(p+i)=='\0')
break;
i++;
}
this->str=new char[i+1];
for(int j=0;j<i;j++)
{
(this->str)[j]=p[j];
}
this->len=i;
/*this->len=strlen(str);
this->str=new char[len+1];
strcpy(this->str,str);*/
}
//判空
bool my_empty();
//求长度
int my_size();
//转换为c风格字符串
char *my_str();
void show()
{
cout<<str<<endl;
}
private:
char *str;
int len;
};
bool my_string::my_empty()
{
if(len==0)
return true;
else
return false;
}
int my_string::my_size()
{
return len;
}
char *my_string::my_str()
{
return str;
}
int main()
{
my_string s1;
s1="hello world";
cout<<s1.my_str()<<endl;
cout<<s1.my_empty()<<endl;
cout<<s1.my_size()<<endl;
s1.show();
my_string s2 = "ni hao";
s2.show();
my_string s3("hqyj");
s3.show();
my_string s4(5,'a');
s4.show();
cout << "Hello World!" << endl;
return 0;
}