Custom string class (C++)

前端 未结 4 1682
灰色年华
灰色年华 2021-01-05 18:23

I\'m trying to write my own C++ String class for educational and need purposes.
The first thing is that I don\'t know that much about operators and that\'s why I want to

4条回答
  •  醉梦人生
    2021-01-05 18:49

    A few mistakes you made:

    1. Copy constructor signature is wrong. It must be:

    CString(const CString& q)
    

    2. op= signature is wrong. It must be:

    CString& operator=(const CString& q)
    

    Btw., that was also the reason that the copy constructor was called. You did a return *thisin the end which copied the object (with your op= signature).

    3. You allow CString instances with cstr == NULL (your default constructor will result in such an instance). Though, in almost all functions (copy constructor, operator +, operator =) you don't handle that case well (q.cstr == NULL).

    Maybe the easiest and safest way would be to just disallow that case and change your default constructor to:

    CString::CString()
    {
       cstr = new char[1];
       cstr[0] = 0;
    }
    

提交回复
热议问题