Custom String Class (C ++)

I am trying to write my own C ++ String class for educational purposes and needs.
Firstly, I don’t know so much about operators and why I want to study them. I started writing my class, but when I run it, it blocks the program, but does not crash.
Take a look at the following code before reading further:

class CString
{
private:
  char* cstr;
public:
  CString();
  CString(char* str);
  CString(CString& str);
  ~CString();

  operator char*();
  operator const char*();
  CString operator+(const CString& q)const;
     CString operator=(const CString& q);
};

First of all, I'm not sure that everything is correct. I tried about this, but all overloading lessons explain the basic idea, which is very simple, but does not allow explaining how and when each thing is called. For example, in the my = statement, the program calls CString (CString & str); but I have no idea why.
I also added a cpp file below:

CString::CString()
{
 cstr=0;
}
CString::CString(char *str)
{
 cstr=new char[strlen(str)];
 strcpy(cstr,str);
}
CString::CString(CString& q)
{
 if(this==&q)
  return;
 cstr = new char[strlen(q.cstr)+1];
 strcpy(cstr,q.cstr);
}
CString::~CString()
{
 if(cstr)
  delete[] cstr;
}
CString::operator char*()
{
 return cstr;
}
CString::operator const char* ()
{
 return cstr;
}
CString CString::operator +(const CString &q) const
{
 CString s;
 s.cstr = new char[strlen(cstr)+strlen(q.cstr)+1];
 strcpy(s.cstr,cstr);
 strcat(s.cstr,q.cstr);
 return s;
}
CString CString::operator =(const CString &q)
{
 if(this!=&q)
 {
  if(cstr)
   delete[] cstr;
  cstr = new char[strlen(q.cstr)+1];
  strcpy(cstr,q.cstr);
 }
 return *this;
}

, CString a = CString ( "Hello" ) + CString ( "" ),
();
, - . 2 "" " ". +, . . "CString (CString & str)", . ? , , "Hello World", ( ). . char * Cstring . =, . printf (a) .
VisualStudio 2010 , ++, , , , .

+5
4

:

cstr=new char[strlen(str)];

:

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

, - - , . ,

, . :

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

:

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

, . CString "Hello world" ( ) , .

, , , .

+4

strlen, . . , const char *, .

, const char * const .

+3

:

  • . "" "". undefined.
  • CString:: operator + 1- CString ( "" ), CString ( "" ) . CString:: operator + - CString
  • , i.e: CString a = [CString result of operator +], ++ . , CString(CString& ), .

, 4 , ( "" "" ), ( CString::operator + (CString a = ...). .

, printf, . :

#include <cstdio>
#include <cstring>

[your code]

int main(int argc,char* argv[]) {
  CString a = CString("hello") + CString(" world");
  printf(a);
}

, hello world . Ubuntu g++ 4.4. , VS .

+1

, :

1. . :

CString(const CString& q)

2. op = . :

CString& operator=(const CString& q)

Btw., . return *this , ( op = signature).

3. CString cstr == NULL ( ). ( , operator +, operator =) (q.cstr == NULL).

, :

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

All Articles