#include <iostream>
#include<cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string()
{
len=0;
str=NULL;
}
//析构函数
~my_string()
{
delete str;
str=NULL;
}
//有参构造
my_string(char c,int l)
{
this->str = new char[l];
for(int i=0;i<l;i++)
{
str[i]=c;
}
str[l]=0;
this->len=l;
}
my_string(char *c)
{
this->len=strlen(c);
this->str=new char[len+1];
strcpy(str,c);
}
//拷贝构造
my_string(const my_string& other)
{
this->len=other.len;
str = new char[other.len+1];
for(int i=0;i<other.len+1;i++)
{
str[i]=*(other.str+i);
}
}
//拷贝赋值
my_string & operator=(const my_string & other)
{
delete this->str;
this->len=other.len;
str = new char[other.len+1];
for(int i=0;i<other.len+1;i++)
{
str[i]=*(other.str+i);
}
return *this;
}
my_string & operator=(char *c)
{
delete this->str;
this->len=strlen(c);
this->str=new char[len+1];
strcpy(str,c);
}
//bool my_empty() 判空
bool my_empty()
{
if(len==0)
return true;
else
return false;
}
//int my_size() 求长度
int my_size()
{
return len;
}
//char *my_str() 转化为c风格字符串
char *my_str()
{
return str;
}
};
int main()
{
//定义一个string类
cout<<"=========string========="<<endl;
string str(5,'A');
cout<<str<<endl;
//定义一个my_string类
cout<<"=======my_string======="<<endl;
my_string str1('A',5);
cout<<str1.my_str()<<endl;
//拷贝构造
cout<<"======copy_create======"<<endl;
my_string str2=str1;
cout<<str2.my_str()<<endl;
//拷贝赋值
cout<<"======copy_assign======"<<endl;
my_string str3;
str3=str1;
cout<<str3.my_str()<<endl;
//判空
cout<<"=======is_empty======="<<endl;
my_string str4;
if(str4.my_empty())
cout<<"str4 empty"<<endl;
else
cout<<"str4 not empty"<<endl;
if(str1.my_empty())
cout<<"str1 empty"<<endl;
else
cout<<"str1 not empty"<<endl;
//求长度
cout<<"=======get_length======="<<endl;
cout<<"str1 length is:"<<str1.my_size()<<endl;
cout<<"str4 length is:"<<str4.my_size()<<endl;
//字符串直接赋值
my_string str5="hello";
cout<<str5.my_str()<<endl;
str5="world";
cout<<str5.my_str()<<endl;
return 0;
}
原文地址:https://www.jb51.cc/wenti/3286497.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。