作业内容
仿照string类,写一个my_string类
class my_string
{
private:
char *str;
int len;
publuc:
//无参构造
//有参构造
//拷贝构造
//拷贝赋值
//bool my_empty() 判空
//int my_size() 求长度
//char *my_str() 转化为c风格字符串
}
要求:前四个必须实现,后三个尽力而为
主要代码
#include <iostream>
#include <cstring>
using namespace std;
class my_string
{
private:
char *str;
int len;
public:
//无参构造
my_string()
{
cout << "无参构造函数" << endl;
}
//有参构造
my_string(char *str)
{
this->str = str;
len = strlen(str);
cout << "有参构造函数" << endl;
}
//拷贝构造
my_string(const my_string &other):str(other.str),len(other.len)
{
cout << "拷贝构造函数" << endl;
}
//拷贝赋值
my_string & operator = (const my_string &other)
{
if(&other != this)
{
this->str = other.str;
this->len = other.len;
}
if(this->str != NULL)
{
delete this->str;
this->str = NULL;
}
this->str = new char(*(other.str));
return *this;
}
~my_string()
{
delete str;
}
//显示函数
void display()
{
cout << str << '\t' << len << endl;
}
//判空
bool my_empty()
{
return strlen(str)==0?true:false;
}
//求长度
int my_size()
{
return strlen(str);
}
//转化为c风格字符串
char *my_str()
{
return str;
}
};
int main()
{
my_string ms1;
char* str = "zhangying";
my_string ms2(str);
cout << ms2.my_empty() << endl;
ms2.display();
my_string ms3(ms2);
cout << ms3.my_empty() << endl;
ms3.display();
my_string ms4 = ms3;
cout << ms4.my_empty() << endl;
ms4.display();
return 0;
}