#include<iostream>
using namespace std;
class String
{
/*String()//无参构造
{
_str=new char[1];
*_str='\0';
}
String(const char *str)//有参构造
{
_str=new char[strlen(str)+1];
strcpy(_str,str);
}
*/
public:
//构造函数
String(const char *str)
{
if (str==NULL)
{
_str=new char[1];//对空字符串自动申请存放结束标志'\0'的空间
*_str='\0';
}
else
{
_str=new char[strlen(str)+1];
strcpy(_str,str);
}
}
//析构
~String()
{
delete []_str;
}
//拷贝构造函数,深拷贝,给拷贝构造的对象重新分配空间
String(const String &str)
{
_str=new char[strlen(str._str)+1];
strcpy(_str,str._str);
}
//拷贝构造函数的现代写法
/*String(const String& s):_str(NULL)//一定要对_str初始化,如果没有初始化,_str的值很可能是一个随机值,其指向的内存空间是不合法的。当tmp._str和_str交换后析构tmp就会出错。
{
String tmp(s._str);
swap(_str,tmp._str);
}*/
//字符串赋值函数,这是重点
String& operator=(String s)
{
swap(_str,s._str);//通过swap将临时变量s中的数据保存到了_str中,同时_str中的数据拷贝到了临时变量中,在函数返回时自动释放
return *this;
}
//现代写法
/*String& operator=(const String& s)
{
if (this->_str != s._str)//if(this!=&s)
{
String tmp(s);
swap(_str,tmp._str);
}
return *this;
}
*/
/*String& String::operator=(const String &str) //输入参数为const
{
if(this == &str) //检查自赋值
return *this;
delete[] _str; //释放原有的内存资源
_str = new char[strlen(str._str) + 1]; //加NULL 判断
strcpy(_str,str._str);
return *this; //返回本对象的引用
}*/
void print()
{
if (_str)
cout<<_str<<endl;
}
private:
char *_str;
};
void test()
{
String s1("we are young");
String s2(s1);
s2.print();
String s3("lallaa");
s3=s1;
s3.print();
}
int main()
{
test();
system("pause");
return 0;
}
①https://blog.csdn.net/m0_38121874/article/details/77836285?depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5&utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromBaidu-5
②https://github.com/chenshuo/recipes/blob/master/string/StringTrivial.h(陈硕)
③https://www.cnblogs.com/zkfopen/p/10606571.html(博客园)
④https://blog.csdn.net/weixin_34129145/article/details/91841717
⑤https://blog.csdn.net/han_shi_lei/article/details/88781486