Now we define a class
Name.h
Class name
{
Private
Char *str;
int Len;
static in Num_name; Global variables that cannot be initialized in a declaration. (because the declaration describes how to allocate memory, but does not allocate memory).
Public
Name ();
Name (const char* s);
Name (const name& s);
~name ();
}
Name.cpp
#include <cstring>
#include <iostream>
using namespace Std;
int name::num_name = 0;
Name::name ()
{
len = 4;
str = new CHAR[LEN+1];
strcpy (str, "C + +");
Num_name + + '
}
Name::name (const char* s)
{
Len = strlen (s);
str = new CHAR[LEN+1];
strcpy (str, s);
Num_name + +;
}
Name::~name ()
{
num_name--;
delete [] str;
}
When we assign an object to another object, the implicit copy constructor of the class is called (the default). The default copy constructor does not describe its behavior, so it does not indicate the creation process, nor does it increase the value of the num_name of the counter.
However, the destructor updates the count and is called when any object expires, regardless of how the object was created.
So, we should show ourselves the definition copy constructor.
Name::name (const name& s)//Display copy constructor
{
num_name++;
............
}
The next exception is more subtle, the implicit copy constructor, which is a shallow copy, which is equivalent to the pointer type: Object A.STR = Object B.str, which simply assigns the string address of B to a string that points to the same address of the same string.
Object A calls the destructor to release str, and when object B calls the destructor to release STR, it is an address that has been disposed of, which creates an unexpected error, so that the object has its own string, so that the object has its own string,
We're going to deep-copy the string.
The copy function is written like this:
Name::name (const name& s)
{
Num_name + +;
len = S.len;
str = new CHAR[LEN+1];
strcpy (str, S.STR);
}
Note: If a class contains pointer members that are initialized with new, you should define a copy constructor to copy the data pointed to, not the pointer, which is called deep copy. Another form of replication (member copy or shallow copy) is just a copy of the pointer,
Shallow copy only shallow copy pointer information, and do not drill down into "mining" to copy the structure of the pointer reference.
Shallow copy and deep copy of class