C++ String面试题

#include <iostream>
using namespace std;

class String
{
private:
	char *pc;

public:
	//注意const的使用
	String(const char *pcStr = NULL) //默认参数
	{
		cout<<"construct"<<endl;
		if (NULL != pcStr)
		{
			pc = new char[strlen(pcStr) + 1];
			memcpy(pc, pcStr, strlen(pcStr) + 1);
			
		}
		else /* 出现空指针的情况 */
		{
			pc = new char[1]; 
			pc[0] = '\0';
		}
	}

	~String()
	{
		cout<<"destroy"<<endl;
		if (NULL != pc)
		{
			delete pc;
			pc = NULL;
		}
	}

	String(const String &str)
	{
		cout<<"copy construct"<<endl;
		if (NULL != str.pc)
		{
			pc = new char[strlen(str.pc) + 1];
			memcpy(pc, str.pc, strlen(str.pc) + 1);
		}
	}

	String& operator=(const String& rhs)
	{
		cout<<"======"<<endl;
		if (&rhs == this) /* 防止自己拷贝自己 */
		{
			return *this;
		}
		/* 删除被赋值对象中指针变量的内存空间,防止内存泄露 */
		if (NULL != pc)
		{
			delete pc;
			pc = NULL;
		}

		pc = new char[strlen(rhs.pc) + 1];
		memcpy(pc, rhs.pc, strlen(rhs.pc) + 1);

		return *this;
	}

	void print()
	{
		if (NULL != pc)
		{
			printf("%s\n", pc);
		}
	}
};

int main(int argc, char** argv) 
{ 
	char *s = "hello";

	String str(s);
	str.print();

	String str2;
	str2.print();

	str2 = str;
	str2.print();

	String str3(str2);
	str3.print();

  
  return 0; 
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值