C++编写类String的构造函数、析构函数和赋值函数
#include<iostream>
#include<string.h>
#include<stdio.h>
using namespace std;
class String
{
public:
String(const char *str = NULL); //普通构造函数
String(const String &other); //拷贝构造函数
~String(); //析构函数
String &operator =(const String &other); //赋值函数
public:
char *m_data; //用于保存字符串
};
String::String(const char *str)
{
if(str != NULL)
{
int len = strlen(str);
m_data = new char[len+1];
strcpy(m_data, str);
}
else
{
m_data = new char[1]; //对空字符串自动申请存放结束标志'\0'的空
*m_data = '\0';
}
}
String::~String()
{
delete [] m_data;
}
String::String(const String &other)
{
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data);
}
String & String::operator=(const String &other)
{
if(this == &other) //检查自赋值
{
return *this;
}
delete [] m_data; //释放原有的内存资源
int len = strlen(other.m_data);
m_data = new char[len+1];
strcpy(m_data, other.m_data);
return *this; //返回本对象的引用
}
int main()
{
String str("hanyufeng");
const String s1="liuyifei";
const char s2[]="liushishi";
printf("%s\n",str.m_data);
printf("s1: %s\n",s1.m_data);
String ss2(s2);
printf("ss2: %s\n",ss2.m_data);
String ss1(s1);
printf("ss1: %s\n",ss1.m_data);
return 0;
}