C++ default copy constructors and assignment constructors are shallow copies, so when you encounter a class member that contains a pointer variable, you have to implement a deep copy yourself!

Const string& other can access private variables?

 

Write the constructor, destructor, and assignment function of class String.

class String { public: String(const char *str=NULL); // The plain constructor String(const string&str); // Copy the constructor string&operator =(const string&str); // The assignment function ~String(); // destructor

private: char* m_data; // Save string};

A:

#include <iostream> #include <string> #include <string.h> using namespace std; class String { public: String(const char *str=NULL); // The plain constructor String(const string&str); // Copy the constructor string&operator =(const string&str); // The assignment function ~String(); // destructor private: char* m_data; // Save string}; // Common constructor String::String(const char * STR) {if (STR ==NULL) {m_data=new char[1]; If (m_data==NULL) {STD ::cout<<" 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) {STD ::cout<<" Memory failed!" <<std::endl; exit(1); } strcpy(m_data,str); }} // Copy constructor String::String(const String &other) {// Input parameter is const int length=strlen(other.m_data); m_data=new char[length+1]; If (m_data==NULL) {STD ::cout<<" Memory failed!" <<std::endl; exit(1); } strcpy(m_data,other.m_data); } // The assignment function string&string ::operator =(const string&other) {// The input parameter is const if (this == &other) // Check the self-assignment {return *this; } delete [] m_data; Int length=strlen(other.m_data); m_data= new char[length+1]; If (m_data==NULL) {STD ::cout<<" Memory failed!" <<std::endl; exit(1); } strcpy(m_data,other.m_data); return *this; // Returns a reference to this object} // Destructor String::~String() {delete [] m_data; } int main() { String a; String b("abc"); a = b; system("pause"); }Copy the code