1.编写MyString类
涉及到的知识:构造函数,默认参数,拷贝函数、析构函数、new和delete、运算符重载operator
类的原型:
class MyString
{
public:
MyString(const char *str = NULL);// 普通构造函数,参数可以默认为空
MyString(const MyString &other); // 拷贝构造函数
~MyString(void); // 析构函数
MyString& operator=(const MyString &other);// 赋值函数,表达式返回的是引用
MyString operator +(const MyString &other);// 连接函数,表达式返回的值
MyString& operator +=(const MyString &other);// 连接赋值函数,表达式返回的是引用
public:
char *p_data; //指向string的指针
};
实现代码:
MyString::MyString(const char *str)// 普通构造函数
{
cout << "MyString::MyString(const char *str = NULL)"<<endl;
if(str ==NULL){ //当str==NULL时,也需要申请内存,是为了和析构函数配对
cout << "str == NULL"<<endl;
p_data = new char[1];
*p_data = '\0';
}else{
int length =strlen(str);
p_data = new char[length+1];//new的语法
strcpy(p_data, str);
}
}
MyString::MyString(const MyString &other) // 拷贝构造函数,传入引用
{
cout << "MyString::MyString(const MyString &other) // 拷贝构造函数"<<endl;
int length =strlen(other.p_data);
p_data = new char[length+1];
strcpy(p_data, other.p_data);
}
MyString& MyString::operator=(const MyString &other)// 赋值函数
{
cout << "MyString& MyString::operator=(const MyString &other)// 赋值函数"<<endl;
if(this == &other){ //可能存在对象自赋值的情况,判断一下提升效率
return *this;
}
delete[] p_data;//先释放原对象空间
int length =strlen(other.p_data);
p_data = new char[length+1];
strcpy(p_data, other.p_data);
return *this;//返回表达式值即左值
}
MyString MyString::operator +(const MyString &other)// 连接函数
{
char *t_data;
cout << "MyString MyString::operator +(const MyString &other)// 连接函数"<<endl;
t_data =new char[strlen(p_data)+strlen(other.p_data)+1];
strcpy(t_data, p_data);
strcat(t_data, other.p_data);
//delete []p_data;
//p_data = t_data;
return MyString(t_data);//返回一个MyString对象
}
MyString& MyString::operator +=(const MyString &other)// 连接赋值函数
{
char *t_data;
cout << "MyString& MyString::operator +=(const MyString &other)// 连接赋值函数"<<endl;
t_data =new char[strlen(p_data)+strlen(other.p_data)+1];
strcpy(t_data, p_data);
strcat(t_data, other.p_data);
delete []p_data;
p_data = t_data;
return *this;
}
MyString::~MyString(void)
{
cout << "MyString::~MyString(void)"<<endl;
delete[] p_data;//char\int等基础类型也可以直接delete p_data;
}