String的构造,析构,赋值,赋值函数编写

本文介绍了一个简单的C++字符串类实现,重点讲解了如何正确实现深拷贝以避免内存泄漏问题。通过构造函数、拷贝构造函数及赋值操作符重载确保每个实例拥有独立的内存空间。
#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; 
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值