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++基本功!