剑指offer 刷题1

题目

如下为类型CMyString的声明,请为该类型添加赋值运算符函数。

 

1

2

3

4

5

6

7

8

9

class CMyString

{

public:

     CMyString(char* pData = nullptr);

     CMyString(const CMyString& str);

     ~CMyString(void);

private:

     char* m_pData;

};

 

2.考查知识点

  • 是否把返回值的类型声明为该类型的引用,并在函数结束的时候返回*this。只有返回一个引用,才可以允许连续赋值。
  • 是否把参数类型声明为常量引用。不是引用,将会调用复制构造函数,造成不必要的浪费。因为赋值运算符不会改变实例状态,因此需要声明为const
  • 是否释放实例自身内存,否则会引起内存泄露(memory leak)。
  • 是否能够实现自身赋值而不会引起错误。
  • 是否考虑到内存分配失败抛出bad_alloc,导致异常退出,还能保证原实例不会被改变。
#include<iostream>
#include<cstring>
using namespace std;
void mystrcpy(char*dea,char*sa);
class mystring{
private:
    char* mydata;
public:
    friend void mystrcpy(char *, char*);
    mystring(char* pdata = nullptr); //constructor function
    mystring(const mystring & str);  // copy constructor function
    mystring& operator = (const mystring & str); //assignment operator
     ~mystring(void);   // destructor function

};
mystring ::mystring(char*pdata ){ //constructor function
    if(pdata == nullptr){
        pdata = new char[1];
        *pdata = '\0';
    }else{
        mydata =new char[(strlen(pdata) + 1)];
        mystrcpy(mydata,pdata);
    }
}

mystring :: mystring(const mystring & str){  //copy constructor function
        mydata = new char[strlen(str.mydata) + 1];
        mystrcpy(mydata,str.mydata);
}
mystring & mystring::operator=(const mystring & str){ //assignment operator function
    if(this == &str)
        return *this;
    else{
        char* temp =new char[strlen(str.mydata)+ 1];
        delete [] mydata;
        mydata = nullptr;
        mydata = temp;
    }
}

/** Another way to implement assignment operator.
 *  1. Self-assignment is considered. (The if condition)
 *	2. Continuous assignment is considered. (Return a reference)
 *	3. Exception is considered. (bad_alloc) 
 */
 
/*CMyString& CMyString::operator=(const CMyString& str)
{
	if (str.m_pData != m_pData)
	{
		CMyString tempStr(str);
		char * pTemp = m_pData;
		m_pData = tempStr.m_pData;
		tempStr.m_pData = pTemp;
		// Note: Exchanging tempStr.m_pData and this.m_pData
		// makes sure that the orignal memory can be freed
		// in tempStr's destructor.
	}
	return *this;
}*/


mystring:: ~mystring(){ // destructor function
    if(mydata != nullptr)
        delete [] mydata;
}
 void mystrcpy(char* dea,char* sa){
    if(dea == sa)
        return  ;
    else{
        while(*sa){
            *dea++ = *sa++;
        }
        *dea = '/0';
    }
}
int main(){
    mystring w1 = "hello!";
    mystring W2(w1);
    mystring w3;
    w3 = W2 = w1;
    return 0;
}

 参考文献,1剑指offer p 25-27

2.http://www.chengkaiblog.com/language/cpp/coding-interview-code-01-assignment-operator.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值