c++ String类的实现

主要是通过这个例子,理解拷贝构造函数和赋值函数的区别:
代码:

#include <iostream>
#include <string.h>
using namespace std;
class String
{
	public:
		//构造函数 
		String(char *str);
		//拷贝构造函数
		String(const String& other);
		//赋值构造函数
		String& operator=(const String& other);
		//析构函数
		~String();
	private:
		char *m_str=NULL; //保存字符串 
};
//构造函数的实现 
String::String(char *str)
{
	cout<<"构造函数"<<endl;
	//如果初始化时没有进行赋值 
	if(str==NULL)
	{
		//分配内存 
		m_str=new char[1];
		//字符串加上结束符 
		m_str[0]='\0'; 
	 } 
	 else{
	 	//+1是由于还有个结束符\0 
	 	m_str=new char[strlen(str)+1];
	 	strcpy(m_str,str);
	 } 
	 
 } 
 //拷贝构造函数
 String::String(const String &other)
 {
 	cout<<"调用拷贝构造函数"<<endl;
 	m_str=new char(strlen(other.m_str)+1);
 	strcpy(m_str,other.m_str);
  } 
 //赋值函数 
String& String::operator=(const String& other)
 {
 	cout<<"调用赋值函数"<<endl;
 	//先删除原理的数据
 	if(m_str!=NULL)
 	{
 		delete []m_str; 
	 }
	 m_str=new char[strlen(other.m_str)+1];
	 strcpy(m_str,other.m_str);
	 //返回this的值 
	 return *this;
	
 }
 //析构函数
 String::~String()
 {
 		cout<<"调用析构函数"<<endl;
 	if(m_str!=NULL)
 	{
 	   delete []m_str;
 	   m_str=NULL;
	 }
  } 
int main()
{

	String a("sda");
	//调用拷贝构造函数 
	String b(a);
	//调用赋值构造函数 
	String c("Sda");
	c=b;
	return 0;
 } 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值