C++

C++ write String constructors copy constructors destructors and assignment functions


C++ write String constructors, copy constructors, destructors, and assignment functions

Write the constructor, destructor and assignment functions of class String. The prototype of class String is known as:

class String
{
public:
String(const char *str = NULL); //  Ordinary constructor
String(const String &other); //  Copy constructor
~ String(void); //  The destructor
String & operate =(const String &other); //  The mutator
private:
char *m_data; //  To hold strings
};
#include <iostream>
class String
{
public:
  String(const char *str=NULL);// Ordinary constructor
  String(const String &str);// Copy constructor
  String & operator =(const String &str);// The mutator
  ~String();// The destructor
protected:
private:
  char* m_data;// To hold strings
};

// Ordinary constructor
String::String(const char *str)
{
  if (str==NULL)
  {
    m_data=new char[1]; // Automatically request end marks for empty strings '\0' The space of
    if (m_data==NULL)
    {// Whether the memory application is successful
     std::cout<<" Application for memory failed! "<<std::endl;
     exit(1);
    }
    m_data[0]='\0';
  }
  else
  {
    int length=strlen(str);
    m_data=new char[length+1];
    if (m_data==NULL)
    {// Whether the memory application is successful
      std::cout<<" Application for memory failed! "<<std::endl;
      exit(1);
    }
    strcpy(m_data,str);
  }
}

// Copy constructor
String::String(const String &other)
{ // The input parameter is const type
  int length=strlen(other.m_data);
  m_data=new char[length+1];
  if (m_data==NULL)
  {// Whether the memory application is successful
    std::cout<<" Application for memory failed! "<<std::endl;
    exit(1);
  }
  strcpy(m_data,other.m_data);
}

// The mutator
String& String::operator =(const String &other)
{// The input parameter is const type
  if (this == &other) // Check self assignment
  { return *this; }

  delete [] m_data;// Free up the original memory resources

  int length=strlen(other.m_data);
  m_data= new char[length+1];
  if (m_data==NULL)
  {// Whether the memory application is successful
    std::cout<<" Application for memory failed! "<<std::endl;
    exit(1);
  }
  strcpy(m_data,other.m_data);

  return *this;// Returns a reference to this object
}

// The destructor
String::~String()
{
  delete [] m_data;
}

void main()
{
  String a;
  String b("abc");
  system("pause");
}

The above is C++ writing String constructor, copy constructor, destructor and assignment function examples, if you have any questions please leave a message or to the site community exchange discussion, thank you for reading, hope to help you, thank you for the support of the site!