string类的构造函数、析构函数、拷贝构造函数和赋值函数
在一些企业面试中面试官经常会让应聘者编写string类的构造函数、析构函数、拷贝构造函数和赋值函数,所以要牢牢掌握
下面是源代码与详细讲解
#include "iostream"
using namespace std;
class String
{
public:
String(const char *str=NULL); //构造函数
String(const String &other); //拷贝构造函数
~String(void); //析构函数
String& operator=(const String &other); //等号操作符重载
ShowString();
private:
char *m_data; //指针
};
String::~String()
{
delete [] m_data; //析构函数,释放地址空间
cout<<"析构函数"<<endl;
}
String::String(const char *str)
{
if (str==NULL)//当初始化串不存在的时候,为m_data申请一个空间存放'\0';
{
m_data=new char[1];
*m_data='\0';
}
else//当初始化串存在的时候,为m_data申请同样大小的空间存放该串;
{
int length=strlen(str);
m_data=new char[length+1];
if (m_data==NULL)
{//内存是否申请成功
cout<<"申请内存失败!"<<endl;
exit(1);
}
strcpy(m_data,str);
}
cout<<"构造函数"<<endl;
}
String::String(const String &other)//拷贝构造函数,功能与构造函数类似。
{
int length=strlen(other.m_data);
m_data=new char[length+1];
if (m_data==NULL)
{//内存是否申请成功
cout<<"申请内存失败!"<<endl;
exit(1);
}
strcpy(m_data,other.m_data);
cout<<"拷贝构造函数"<<endl;
}
String& String::operator =(const String &other)
{
cout<<"赋值函数"<<endl;
if (this==&other)//当地址相同时,直接返回;
return *this;
//cout<<"赋值函数"<<endl;
delete [] m_data;//当地址不相同时,删除原来申请的空间,重新开始构造;
int length= strlen (other.m_data);
m_data=new char[length+1];
if (m_data==NULL)
{//内存是否申请成功
cout<<"申请内存失败!"<<endl;
exit(1);
}
strcpy(m_data,other.m_data);
return *this; //// 返回的是 *this 的引用,无需拷贝过程
//cout<<"赋值函数"<<endl;
}
String::ShowString()//由于m_data是私有成员,对象只能通过public成员函数来访问;
{
cout<<this->m_data<<endl;
}
main()
{
String AD="abc";//调用构造函数
char * p="ABC";
String B(p);//调用构造函数
//String AD=B; 如果把主函数的第一行注释掉,则此语句调用的是拷贝构造函数,因为AD还没有实例化,需要调用拷贝构造函数进行创建来构造出AD
AD.ShowString();
AD=B;//调用赋值函数
AD.ShowString();
return 0;
}执行结果
最后说一下如果主函数改为
main()
{
char * p="ABC";
String B(p);//调用构造函数
String AD=B; //如果把主函数的第一行注释掉,则此语句调用的是拷贝构造函数,因为AD还没有实例化,需要调用拷贝构造函数进行创建来构造出AD
AD.ShowString();
return 0;
}
{
char * p="ABC";
String B(p);//调用构造函数
String AD=B; //如果把主函数的第一行注释掉,则此语句调用的是拷贝构造函数,因为AD还没有实例化,需要调用拷贝构造函数进行创建来构造出AD
AD.ShowString();
return 0;
}
则执行结果为
925

被折叠的 条评论
为什么被折叠?



