C + + construction and destructor

Constructor

  • What does a constructor look like
    -The function name is the same as the class name
    -No return value
    void also has a return value
    -If you do not write a constructor, there is a default constructor in any class
    The default constructor is parameterless
    When we write the constructor, the default function is deleted
    -Constructor is called by default when constructing an object
    -Delete can be used to delete the default constructor
    Class name () = delete;
    -Specifies to use the default parameterless constructor, described with default
    Class name () = default;
    -Allow a constructor to call another constructor, just by initializing the parameter list
    -Initialization parameter list: only constructors have
    Constructor name (parameter 1, parameter 2...): member 1 (parameter 1), member 2 (parameter 2)... {} (avoid problems caused by the same formal parameter and data member)
  • What are constructors for
    -Used to construct objects
    -Constructors are more used for tree pool data members
  • Some thoughts on constructor
    -Why not write a constructor to construct an object? (because there is a default parameterless constructor, you can only construct parameterless objects when you don't write again)
    -Why should constructors be overloaded? (to construct objects with different looks)
//Initialization parameter list
class Tihu1{
	public:
		Tihu1(string nname = "Tihu",int nage = 19):name(nname),age(nage){}
		void print(){
			cout<<name<<"\t"<<age<<endl;
		}
	protected:
			string name ;
			int age ;
};
//Default of constructor 
class Tihu2{
	public:
		Tihu2(string nname = "Tihu two",int nage = 19){
			name = nname;
			age = nage;	
			}	
		void print(){
			cout<<name<<"\t"<<age<<endl;
		}
	protected:
			string name ;
			int age ;
};
int main(void){
	Tihu1 A1("Tihu1",20);
	Tihu1 A2("Tihu2",21);
	Tihu2 A3;
	A1.print();
	A2.print();
	A3.print();	
	return 0;
}

Destructor

  • What does a destructor look like
    • No return value
    • No parameters
    • Function name: class name
    • If it is not written, there is a default destructor
    • Destructors do not need to be called by themselves and are executed at the end of the object's life cycle
  • What are destructors for
    -When the data member in the class is a pointer, use dynamic memory to apply for writing constructors and destructors
    -Freeing dynamic memory requested by data members
class Tihu2{
	public:
		Tihu2(const char *nname ="Tihu",int nage = 19){
			name = new char[strlen(nname)+1];
			strcpy(name,nname);
			cout<<strlen(nname)+1<<endl;
			age = nage;	
			}	
		void print(){
			cout<<name<<"\t"<<age<<endl;
		}
		//Destructor
		~Tihu2(){
			cout<<"I'm a destructor"<<endl; 
			delete [] name;
		}
	protected:
			char* name ;
			int age ;
};

copy constructor

  • The copy constructor is also a constructor. It looks the same as the constructor. It is also used to construct objects, but
    Parameters are unique and are references to objects
    Tihu(const Tihu& A1 )
  • If it is not written, there is a default copy to construct the function, but the default is a shallow copy, which is not applicable when the element contains a pointer.
  • Copy constructor is used to initialize one object with another
  • const must be added when there is an anonymous object assignment operation
class Tihu
{
	public:
	//Definition method of copy structure
	Tihu(const Tihu& A1)
	{
		age = A1.age;
	}
	protected:
	int age;
}

Deep copy and shallow copy

  • Shallow copy: the default copy structure is shallow copy
  • Deep copy: a new memory operation is performed in the copy structure, because when the shallow copy has a pointer, it only determines the pointer, not applies for new space for the pointer, resulting in an error in memory release in the destructor
class Tihu
{
	public:
	Tihu(char nname[] = "Tihu",int nage = 19):age(nage)
	{
		name = new char[strlen(nname)+1];
		strcpy(name,nname);
	}
	Tihu(const Tihu& A1)
	{
		name = new char[sizeof(*A1.name)];
		strcpy(name,A1.name);
	}
	~Tihu()
	{
		delete[] name;
	}
	protected:
		char* name;
		int age;
}

Tihu A1("Tihu1",10);
Tihu A2(A1);
printf("A1.name:%p\n",A1.name);
printf("A2.name:%p\n",A2.name);

Tectonic and destructional sequence

  • For ordinary objects, the construction order and destruction order are opposite
  • delete will directly call the destructor for the new object
  • static object. The life cycle ends when the program is closed
#include <iostream>
#include <string>
using namespace std;
class MM 
{
public:
	MM(string name="x") :name(name) {
		cout << name;
	}
	~MM(){
		cout << name;
	}
protected:
	string name;
};
int main() 
{
	{
		MM mm1("A");			//A
		static MM mm2("B");		//B program dies when it is closed, and finally destructs
		MM* p3 = new MM("C");	//C
		MM mm4[4];				//xxxx
		delete p3;				//C delete calls the destructor directly
		p3 = nullptr;
								//xxxxAB
	}
	//ABCxxxxCxxxxAB
	return 0;
}

C + + structure

  • If a constructor is added to the structure of c + +, the c + + class must be used. The only difference is that the default area in the structure is a public attribute, while the default area in the class is a private attribute.

task

  • Implementation of mystring class
    1. Implement the creation method in string
    2. By implementing data and c_str function prints a string
    3. Implement the link of append string
    4. Implement string comparison
    5. Freeing memory by handwriting destructor
 #include <iostream>
 #include <cstring> 
 using namespace std;
 /* 
 mystring Class implementation
 	1. Implement the creation method in string
 	2. By implementing data and c_str function prints a string
 	3. Implement the link of append string
 	4. Implement string comparison
 	5. Freeing memory by handwriting destructor
*/
class mystring
{
	public:
		mystring(char str1[]="Default value"){
			str = new char[strlen(str1)+1];
			strcpy(str,str1);
		}
		mystring(const mystring& object){
			str = new char[strlen(object.str)+1];
			strcpy(str,object.str);
		}
		//5. Freeing memory by handwriting destructor
		~mystring(){
			delete[] str;
		}
		char* data(){
			return str;
		} 
		char* c_str(){
			return str;
		}
		void print(){
			cout<<str<<endl;
		}
		mystring append(const mystring& object){
			int n=strlen(str);
			int sum = n+strlen(object.str)+1;
			char* ptemp = new char[sum];
			int i=0;
			while(1){
				if(i<strlen(str)){
					ptemp[i] = str[i];
				}
				else if(i>=strlen(str)&&i<sum-1){
					ptemp[i] = object.str[i-n];
				}
				else{
					ptemp[i] = 0;
					break;
				}		
			}
			mystring A1(ptemp);
			delete[] ptemp;
			ptemp = NULL;
			return A1;
		}
		int compare(const mystring& object){
			return strcmp(str,object.str);
		} 
	protected:
		char* str;		
}; 
int main(){
	//	1. Implement the creation method in string
	mystring str1;
	mystring str2("ILoveyou");
	mystring str3(str1);
	str3.print();
	mystring str4 = str2;
	str4.print();
	//2. By implementing data and c_str function prints a string
	cout << str2.c_str() << endl;  //Print ILoveyou
	cout << str2.data() << endl;   //Print ILoveyou
	//3. Implement the link of append string
	string strOne="one";
	string strTwo="two";
	string strThree=strOne.append(strTwo);
	cout<<strThree.data()<<endl;	    //onetwo
	//4. String comparison
	cout<<strOne.compare(strOne)<<endl;	//0
	cout<<strOne.compare(strTwo)<<endl;	//-1
	cout<<strTwo.compare(strOne)<<endl;	//1
	//5. Freeing memory by handwriting destructor
	
	return 0;
}
  • Operation results

Tags: C C++ Visual Studio

Posted on Mon, 22 Nov 2021 06:55:13 -0500 by sd9sd