Use and explanation of C++ constructors and destructors

  • 2020-06-12 10:12:32
  • OfStack

Constructor (constructor)

1. A constructor is a special class member function that follows the following rules:

a. The function name must be the same as the class name. b. No return value

Such as:


class Obj
{
...
public:
   Obj()
   {
     ...
   }
};

2. Constructors can take arguments or be overloaded


class Obj
{
...
public:
   Obj()
   {
    ...
   }
   Obj(int x, int y)
   {
    ...
   }
};

3. Constructor and normal member function are not the same, 1 usually does not show the call. The constructor is called automatically when an object is created (done by the compiler).

Destructor (destructor)

1. Destructor and construction are 1 opposite procedure, the constructor is called when the object is created, and the destructor is called when the object is destroyed, following the following rules:

a. Fixed name, tilde before class name ~ b. No return value c. Cannot take parameters

For example,


class Obj
{
public:
  ~Obj()
   {
   }
};

2. There can only be one destructor and overloading is not allowed.

3. The destructor does not display the call and is automatically called by the compiler when the object is destroyed.

Re-implement the linked list (using classes, constructs, and destructors)

Create the ES33en.h header file


#ifndef _OBJECT_H_
#define _OBJECT_H_
struct Student
{
 char name[32];
 int age;
 Student* pNext;
};
class DataObj
{
public:
 DataObj();
 ~DataObj();
 void add(Student* pStu);
 void find(int age);
 void printNode(Student* pNode);
private:
 Student m_head;
};
#endif

Create the DataObj.cpp source file


#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "DataObj.h"
// Construct a header linked list 
DataObj::DataObj()
{
 m_head.pNext = NULL;
}
DataObj::~DataObj()
{
 // Point to the head of each node 
 Student* p = m_head.pNext;
 // Release all nodes 
 while(p)
 {
 Student *next = p->pNext;
 free(p);
 p = next;
 }
}
void DataObj::add(Student* pNode)
{
 // Point to the head of each node 
 Student* p = &m_head;
 // Find the end node of the list by the head node 
 while (p)
 {
 if (p->pNext == NULL)
 {
  break;
 }
 p = p->pNext;
 }
 // Add nodes to the tail 
 p->pNext = pNode;
}
void DataObj::find(int age)
{
 // Whether the tag was found 
 bool bFind = false;
 Student* p = &m_head;
 while(p)
 {
 if (p->age == age)
 {
  bFind = true;
  printNode(p);
 }
 p = p->pNext;
 }
 if (!bFind)
 {
 printf(" Failed to find the right age The nodes of the ");
 }
}
void DataObj::printNode(Student* pNode)
{
 printf("name = %s, age = %d\n", pNode->name, pNode->age);
}
int main()
{
 // Tectonic node 
 Student* pStu = (Student*) malloc(sizeof(Student));
 strcpy(pStu->name, "aaaa");
 pStu->age = 30;
 pStu->pNext = NULL;
 {
 DataObj dataObj;
 // Add a node 
 dataObj.add(pStu);
 // Find nodes 
 dataObj.find(31);
 }
 return 1;
}

conclusion


Related articles: