#include<iostream>
#include<cstring>
#include<cstdlib>
using namespace std;
class String
{
public:
String(const char *str);//构造函数
~String();//析构函数
String(const String &other);//复制函数
String &operator= (const String &other);//赋值操作符
public:
char *m_data;//保存字符串
};
String::String(const char *str)
{
if(str==NULL)
{
m_data=(char*)malloc(1);
*m_data='\0';
cout << "Construcing null." << endl;
}
else
{
m_data=(char*)malloc(sizeof(strlen(str)+1));
strcpy(m_data,str);
cout << "Construcing success." << endl;
}
}
String::~String()
{
if(m_data!=NULL)
{
free(m_data);
m_data=NULL;
}
cout << "Destructing success."<< endl;
}
String::String(const String &other)
{
int length = strlen(other.m_data);
m_data=(char*)malloc(sizeof(length+1));
strcpy(m_data,other.m_data);
cout << "Constructing Copy success." << endl;
}
String& String::operator=(const String &other)
{
if(this==&other)
return *this;
free(m_data);
m_data=NULL;
int length = strlen(other.m_data);
m_data=(char*)malloc(sizeof(length+1));
strcpy(m_data,other.m_data);
cout << "Operate = Function success." << endl;
return *this;
}
int main()
{
String a("hello"); //调用普通构造函数
cout<<"a:"<<a.m_data<<endl;
String b("world"); //调用普通构造函数
cout<<"b:"<<b.m_data<<endl;
String c(a); //调用拷贝构造函数
cout<<"c:"<<c.m_data<<endl;
c = b; //调用赋值函数
cout<<"c:"<<c.m_data<<endl;
return 0;
}
String的构造,析构,赋值,赋值函数编写
最新推荐文章于 2024-01-27 23:17:37 发布
本文介绍了一个简单的C++字符串类实现,重点讲解了如何正确实现深拷贝以避免内存泄漏问题。通过构造函数、拷贝构造函数及赋值操作符重载确保每个实例拥有独立的内存空间。
2589

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



