代码:
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string(){}
//有参构造
my_string(char *s){
//cout<<"调用了有参构造1"<<endl;
str=new char[128];
memset(str,0,sizeof(str));
strcpy(str,s);
}
my_string(int n,char ch){
//cout<<"调用了有参构造2"<<endl;
int i;
str=new char[128];
memset(str,0,sizeof(str));
for(i=0;i<n;i++){
str[i]=ch;
}
str[i]='\0';
//str=arr;
}
//拷贝构造
my_string(const my_string& O){
//cout<<"调用了拷贝构造"<<endl;
this->str=new char[128];
memset(str,0,sizeof(str));
strcpy(this->str,O.str);
this->len=O.len;
}
//拷贝赋值
my_string& operator=(const my_string& R){
//cout<<"调用了赋值构造"<<endl;
this->str=new char[128];
memset(str,0,sizeof(str));
strcpy(this->str,R.str);
this->len=R.len;
}
//析构函数
~my_string(){
delete str;
}
int getLen(){
return len;
}
//判空
bool my_empty(){
if(strlen(str)==0)
return true;
else
return false;
}
//求长度
int my_size(){
return strlen(str);
}
//转换为c分格字符串
char *my_str(){
return str;
}
};
int main()
{
//验证有参构造
my_string str1("hello world!");
cout<<"str1:"<<str1.my_str()<<endl;
my_string str2(10,'h');
cout<<"str2:"<<str2.my_str()<<endl;
//验证拷贝构造
my_string str3=str1;
cout<<"str3"<<str3.my_str()<<endl;
//验证赋值构造
my_string str4;
str4=str3;
//验证判空
my_string str5("");
if(str5.my_empty())
cout<<"str5空"<<endl;
else
cout<<"str5非空"<<endl;
if(str4.my_empty())
cout<<"str4空"<<endl;
else
cout<<"str4非空"<<endl;
//获取长度
int len=str1.my_size();
cout<<"str1长度为:"<<len<<endl;
return 0;
}
运行结果: