C++string构造、析构的实现

class String{
private:
	char* m_str;	
public:
	String(const char* str=NULL);//普通构造
	~String();//析构函数
	String(const String& other);//拷贝构造
	void print_str(void){
		cout << "m_String:" << m_str << endl;
	}
	//void  operator=(const String &other);//赋值函数
	String& operator = (const String &other);//赋值函数
};

String::String(const char* str){
	if (str==NULL){
		m_str = new char[1];
		*m_str = '\0';
	}
	else
	{
		m_str = new char[strlen(str) + 1];
		strcpy(m_str,str);
	}
}

String::~String(void){
	if (m_str!=nullptr){		
		delete[]m_str;
		m_str = nullptr;		
	}
}
String::String(const String& other){
	if (other.m_str==NULL){ //也可以不做判断,引用不可能为空
		m_str = new char[1];
		*m_str = '\0';
	}
	else{
		m_str = new char[strlen(other.m_str) + 1];
		strcpy(m_str, other.m_str);
	}
	
}
//赋值1
//void String::operator=(const String &other){
//	if (m_str){
//		delete []m_str;
//	}
//	if (other.m_str==NULL){
//		m_str = new char[1];
//		*m_str = '\0';
//	}
//	m_str = new char[strlen(other.m_str) + 1];
//	strcpy(m_str,other.m_str);
//}

//赋值2
String& String::operator = (const String &other){
	if (this==&other){//判断是否和参数other为同一个对象
		return *this;
	}
	delete[]m_str;
	m_str = new char[strlen(other.m_str) + 1];
	strcpy(m_str,other.m_str);
	
	return *this;
}
int _tmain(int argc, _TCHAR* argv[])
{
	String a("hello world");//构造
	a.print_str();
	cout << "---------------" << endl;
	String c(a);//拷贝构造
	c.print_str();
	String b = a;//拷贝构造
	b.print_str();
	c = a;//赋值函数
	c.print_str();
	system("pause");
	return 0;
	//最后执行析构函数
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值