#include <iostream>
#include<cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
my_string()//无参构造
{
}
my_string(const char *s)//有参构造
{
str=new char[128];
memset(str,0,128);
strcpy(str,s);
}
my_string(int n,char ch)
{
int i;
str=new char[128];
memset(str,0,128);
for(i=0;i<n;i++)
{
str[i]=ch;
}
str[i]='\0';
}
my_string(const my_string &other)//拷贝构造
{
this->str=new char[128];
memset(str,0,128);
strcpy(this->str,other.str);
this->len=other.len;
}
my_string& operator=(const my_string &other)//拷贝赋值
{
this->str=new char[128];
memset(this->str,0,128);
strcpy(this->str,other.str);
return *this;
}
~my_string()//析构函数
{
delete str;
}
bool my_empty()//判空
{
if(strlen(str)==0)
{
return 1;
}else{
return 0;
}
}
int my_size()//求长度
{
int size=static_cast<int>(strlen(str));
return size;
}
char& at(int pos)//at()
{
char *btr=new char[128];
memset(btr,0,128);
strcpy(btr,str);
return btr[pos];
}
char* my_str()//转换C风格字符串
{
return str;
}
};
int main()
{
my_string s1("oh my girl");
cout<<s1.my_str()<<endl;
my_string s2(3,'-');
cout<<s2.my_str()<<endl;
my_string s3=s1;
cout<<s3.my_str()<<endl;
my_string s4;
s4=s3;
my_string s5("");
cout<<s5.my_empty()<<endl;
cout<<s4.my_empty()<<endl;
cout<<s1.at(3)<<endl;
cout<<s1.my_size()<<endl;
return 0;
}
2022.9.28
于 2022-09-28 19:57:59 首次发布