标题:String函数的实现-->主要实现构造函数,拷贝构造函数,析构函数,赋值构造函数。这几个函数是字符串函数最基本的函数,今天也总结一下
#include<iostream>
using namespace std;
#include<string.h>
class MyString
{
private:
char *str;
public:
MyString(const char *pStr)//构造函数
{
if(pStr==NULL)
{
str=new char[1];
*str='\0';
}
else
{
str=new char[strlen(pStr)+1];
strcpy(str,pStr);
}
}
MyString(const MyString &other)//拷贝构造函数,必须用引用传递,
//如果不用引用传递将会出现无限递归循环
{
if(this==&other)
return;
str=new char[strlen(other.str)+1];
strcpy(str,other.str);
}
~MyString()//析构函数
{
delete []str;
str=NULL;//防止野指针
}
//最简单直接的写法(赋值函数)用引用返回为了连续赋值
/*MyString& operator=(const MyString &other)
{
if(this != &other)
{
delete []str;
str=new char[strlen(other.str)+1];
strcpy(str,other.str);
}
return *this;
}*/
//高级程序员的写法(赋值函数)
MyString& operator=(const MyString &other)
{
if(this != &other)
{
MyString Tmp(other);//交换指向的地址,然后退出if语句后自动调用析构函数释放之前的内存
char *ret=Tmp.str;
Tmp.str=str;
str=ret;
}
return *this;//返回*this
}
void show()const
{
cout<<"str="<<str<<endl;
}
};