C++ implements the String class instance code
- 2020-05-17 06:05:22
- OfStack
C++ implements the String class instance code
This is a 10-point classic interview question, which can test whether students have a comprehensive grasp of C++ in a short time. The answer should include most of the knowledge of C++ class, ensuring that the String class can complete the functions of assignment, copy and variable definition.
#include<iostream>
using namespace std;
class String
{
public:
String(const char *str=NULL);
String(const String &other);
~String(void);
String &operator =(const String &other);
private:
char *m_data;
};
String::String(const char *str)
{
cout<<" The constructor is called "<<endl;
if(str==NULL)// Avoid wild Pointers, such as String b; If not, there would be wild
// Pointer to the
{
m_data=new char[1];
*m_data=''/0'';
}
else
{
int length=strlen(str);
m_data=new char[length+1];
strcpy(m_data,str);
}
}
String::~String(void)
{
delete m_data;
cout<<" The destructor is called "<<endl;
}
String::String(const String &other)
{
cout<<" The assignment constructor is called "<<endl;
int length=strlen(other.m_data);
m_data=new char[length+1];
strcpy(m_data,other.m_data);
}
String &String::operator=(const String &other)
{
cout<<" The assignment function is called "<<endl;
if(this==&other)// If you copy yourself, you don't have to copy yourself
return *this;
delete m_data;// Deletes the pointer variable before it is pointed to in the assigned object 1 Two memory Spaces to avoid
// A memory leak
int length=strlen(other.m_data);// Calculate the length of the
m_data=new char[length+1];// To apply for space
strcpy(m_data,other.m_data);// copy
return *this;
}
void main()
{
String b;// Call constructor
String a("Hello");// Call constructor
String c("World");// Call constructor
String d=a;// Call the assignment constructor because it is in d Used during object creation a To initialize the
d=c;// Call the overloaded assignment function
}
Thank you for reading, I hope to help you, thank you for your support of this site!