Coding Interviews 1

Source: Internet
Author: User

The first day. Chapter 1&2

Implement assignment function for below class cmystring.

class cmystring{public:    cmystring (char* pData = NULL);    CMyString (const cmystring& str);     ~cmystring (void); Private :     Char* m_pdata;};

Before coding I should focus on four points:

1 Whether The type of return value is the reference of CMyString, and returning the object itself (*this). If only return a reference, I can assign continuously like STR1=STR2=STR3. Otherwise, the codes cannot be compiled.

2 If The parameter is not a const cmystring& from formal parameter to actual parameter The Constructer would be invoked. Reference won't cause this kind of waste and increase the efficiency. Const can help you don't change the parameter for safety.

3 before get a new chunk of memory, I should release the existing memory first, in case of memory leak.

4 Make a judgment on whether the parameter is the same as (*this). If They is same, then return *this. If don ' t a judgment, you'll release the memory of parameter too. You'll not find the source of assignment.

cmystring& cmystring::operator= (const cmystring& str) {    if (  this = = &str        )return * this;     Delete [] m_pdata;     = NULL;     New Char 1 ];    strcpy (M_pdata, str.m_pdata);     return *this;}

More advanced Code

 cmystring& cmystring::operator  = ( Const  Cmystring& str) { if  ( Span style= "color: #0000ff;" >this  = = &str)  return  *this  ;         else   {cmystring tmp (str);         char  * ctmp = M_pdata;        M_pdata  = Tmp.m_pdata;    Tmp.m_pdata  = ctmp;  return  *this  ;}

In this code, we consider about the problem on new. If the memory is not enough, then before we change the content of original object. The exception Bad_alloc is thrown out.

Coding Interviews 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.