C++ string类构造函数

C++笔试时常考的string类构造函数实现:

 

class CString
{
public:
CString (const char* str = NULL);//普通构造函数,默认str为NULL
CString (const CString &other);//拷贝构造函数
~CString();//析构函数
CString& operator =(const CString &other);//赋值函数

private:
	char * m_pchar;//用于保存字符串

};

/*类实现*/
CString::CString(const char *str)
{
	if (str == NULL) //判断是否为空
	{
		m_pchar = new char[1];//对空字符串自动申请存放1字节的结束标志'\0'  对m_charData加NULL 判断
		*m_pchar = '\0';
	}
	else
	{
		int strLength = strlen(str);
		m_pchar = new char[strLength+1];
		//m_pchar = str;
		strcpy(m_pchar,str);//拷贝
	}
}

CString::~CString(void)
{
	delete[] m_pchar;
	m_pchar = NULL;
}

CString::CString(const CString &other)
{
	int Length = strlen(other.m_pchar+1);
	m_pchar = new char[Length];
	strcpy(m_pchar, other.m_pchar);
}

CString& CString:: operator =(CString &other)
{
	if (this == other)// 检查赋值内容
	{
		return *this;
		
	}
	delete[] m_pchar;// 释放原有的内存资源
	int Length = strlen(other.m_pchar);
	m_pchar = new char[Length+1];// 对m_pchar加NULL判断
	strcpy(m_pchar, other.m_pchar);
	return *this;// 返回本对象的使用
}

//赋值函数异常安全性的解法
CString & CString::operator =(CString &other){
    if (this != &other){
        //临时实例
        CString strTemp(other);
        //临时指针
        char* pTemp = strTemp.m_pchar;
        //临时实例与自身实例交换,strTemp 生命周期结束时调用其析构函数,
        //相当于释放了自身m_pchar的原有内容
        strTemp.m_pchar = m_pchar;
        m_pchar = pTemp;
    }
}


 

剖析: 

  能够准确无误地编写出String类的构造函数、拷贝构造函数、赋值函数和析构函数的面试者至少已经具备了C++基本功的60%以上!在这个类中包括了指针类成员变量m_data,当类中包括指针类成员变量时,一定要重载其拷贝构造函数、赋值函数和析构函数,这既是对C++程序员的基本要求,也是《Effective C++》中特别强调的条款。仔细学习这个类,特别注意加注释的得分点和加分点的意义,这样就具备了60%以上的C++基本功!


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值