c++ write String class code instance

  • 2020-06-15 09:56:49
  • OfStack

This article example Shared c++ to write String class specific code for your reference, the specific content is as follows


class String
{
public:
  String(const char* = nullptr); // Ordinary constructor 
  String(const String& other);  // Copy constructor 
  ~String(void); // The destructor 
  String& operator = (const String& other);  // The mutator 
  
private:
  char* m_data;
};
 
// Ordinary constructor 
String::String(const char* str)
{
  if(str == nullptr){
    m_data = new char[1];  // Automatically applies for an end mark for null characters '\0' The empty 
    *m_data = '\0';
  }else{
    m_data = new char[strlen(str) + 1];  //+1 To make it redundant 1 Character storage '\0'
    strcpy(m_data, str);
  }
}
 
// Copy constructor 
String::String(const String& other)
{
  if(other == nullptr){
    m_data = nullptr;
  }else{
    // Notice all of the parentheses down here other.m_data
    m_data = new char[strlen(other.m_data) + 1];
    strcpy(m_data, other.m_data);
  }
}
 
// The destructor 
String::~String(void)
{
  if(m_data != nullptr){
    delete [] m_data;
    m_data = nullptr;
  }
}
 
// Assignment operator 
String& String::operator=(const String& other)
{
  // Determine if you assign yourself a value 
  if(this != other){
    delete [] m_data;  // I'm going to free up the memory 
    if(other == nullptr){
      m_data = nullptr;
    }else{ 
      m_data = new char[strlen(other.m_data) + 1];
      strcpy(m_data, other.m_data);
    }
  }
  return *this;
}

The other two are the overload + sign and the = sign


String& operator + (String& other)
{
  char* tmp = m_data;
  m_data = new char[strlen(m_data) + strlen(other.m_data) + 1];
  strcpy(m_data, tmp);  // Copy the first 1 A string 
  strcpy(m_data, other.m_data);  // Copy the first 2 A string 
  delete [] tmp; // Remember to delete this memory 
  return *this;
}
 
String& operator = (String& other)
{
  if(this = other){
    return *this;
  }
  if(m_data != nullptr){
    delete [] m_data;  // Let's free up the memory 
  }
  m_data = new char [strlen(other.m_data) + 1];
  strcpy(m_data, other.m_data);
  return *this;
}
 

Related articles: