Custom string class (C++)

前端 未结 4 1713
灰色年华
灰色年华 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:44

    The line:

    cstr=new char[strlen(str)];
    

    should be:

    cstr=new char[strlen(str) + 1];
    

    Also, the test for self-assignment does not make sense in the copy constructor - you are creating a new object - it cannot possibly have the same address as any existing object. And the copy constructor should take a const reference as a parameter,

    If in your code, you were expecting the assignment operator to be used, you would be expectining wrong. This code:

    CString a = CString("Hello") + CString(" World");
    

    is essentially the same as:

    CString a( CString("Hello") + CString(" World") );
    

    which is copy construction, not assignment. The temporary CString "Hello world" will be destroyed (invoking the destructor) after a has been constructed.

    Basically, it sounds as if your code is working more or less as expected.

提交回复
热议问题