C++ expedition package part 1

Course introduction

  • Classes (abstract concepts), objects (real concrete)
  • Supporting roles: Data members and member functions (which make up a wonderful and complete class)
  • Constructors & destructors (which describe how objects live and die)
  • Object copy and object assignment (making class definitions art)
  • Object arrays and object Pointers (use application types to their fullest)
  • This pointer (shadow, which runs through the play, but rarely emerges)

You’re going to go from process oriented to object oriented. Handle more complex programs.

When you’re done, do a maze pathfinding program.

Classes and objects

  • Classes (concepts, abstracted from objects) and objects (concrete things)

A faithful friend of man:

Dogs have their own dog information as well as their own skills. A dog is an object, and multiple dogs create tables for a large group of dogs for easy management.

In addition to spreadsheet information, they have common skills: barking and running

From the dog above, we can abstract a dog.

Data members (attributes), member functions (methods)

Consider: is the abstraction all the dog information

Conclusion: Different purposes abstract different information, we only abstract the information we need.

From the nameplate on the TV, we can get its attribute information. We can operate the television set by means of knobs, etc.

Encapsulation: Selective exposure (encapsulating implementation details and exposing only the details that users care about).

All this information is defined in the class. How do you expose what you want to expose and hide what you want to hide?

Access qualifiers: public public, protected, private

Content Summary:

  • What is a class and what is an object
  • Class definition: data member, member function
  • Class access qualifier (public Private)

C++ class object definition

Instantiation of an object

Instantiating an object from a class is the process by which the computer creates multiple objects based on the template of the class.

There are two ways to instantiate an object:

  • Instantiate from the stack
  • Instantiate from the heap

Instantiate objects from the stack

2-2-StackInstantiatedObject/main.cpp

#include <iostream>
#include <stdlib.h>
using namespace std;

class TV
{
   public:
	  char name[20];
	  int type;

	  void changeVol(a);
	  void power(a);
};

int main(void)
{
	TV tv;// Define an object
	// TV tv[20]; // Define an array of objects
	return 0;
}// Instantiating objects from the stack is automatically recycled
Copy the code

Note that you must add; after the class definition is complete.

Instantiate objects from the heap.

  • Objects instantiated from the heap. We need to manually manage new DELETE
  • Requests for instantiations from the stack do not require manual maintenance. The system will automatically reclaim it.
int main(void)
{
	TV *p = new TV(); Instantiate an object in the heap
	// TV *q = new TV[20]; // Define an array of objects

	delete p;
	// delete []q;

	return 0;
}// Instantiate objects from the heap
Copy the code

The new operator allocates memory that is on the heap.

The instantiated object is, of course, not a decoration; we do this by accessing various members of the object.

Object member access

Objects instantiated in different ways have different access modes on object members and member functions.

Stack instantiated out of the object used. Object member access.


int main(void)
{
	TV tv;// Define an object
	tv.type = 0;
	tv.changeVol();
	return 0;
}// instantiate objects from the stack for automatic collection
Copy the code

Objects instantiated by the heap use -> for object member access.

int main(void)
{
	TV *p = new TV();
	p -> type = 0;
	p -> changeVol();

	delete p;
	p = NULL;

	return 0;

}// Instantiate objects from the heap
Copy the code

An example of this code is provided when the objects instantiated in the heap are arrays:

int main(void)
{
	
	TV *q = new TV[5];
	for (int i = 0; i < 5; ++i)
	{
		p[i] ->type =0;
		p[i] ->changeVol();
	}

	delete []q;
	p = NULL;
	return 0;

}// Instantiate objects from the heap
Copy the code

Code demo:

Define a coordinate class that contains x and y data members. Print x and y member functions, respectively.

The name of the class is best to show what the class does

2-2-CoordinateClassStackHeap/main.cpp

#include <stdlib.h>
#include <iostream>
using namespace std;

class Coordinate {
public:
	int x;
	int y;
	void printx(a){
		cout << x << endl;
	}
	void printy(a) {
		cout << y << endl; }};int main(void)
{
	Coordinate coor;
	coor.x = 10;
	coor.y = 20;
	coor.printx();
	coor.printy();

	Coordinate *p = new Coordinate();
	if (NULL == p) {
		//failed
		return 0;
	}
	p->x = 100;
	p->y = 200;
	p->printx();
	p->printy();

	delete p;
	p = NULL;

	system("pause");
	return 0;
}
Copy the code

If memory allocation fails, the memory is released and the pointer is empty.

C++ initializes String

Frequently used and cumbersome data operation:

These are frequently used but easily manipulated data types.

  • Char array:

An array of strings operating functions: (strlen | strcat | strcpy | STRCMP | strncpy | STRNCMP | STRSTR)

  • String Type The type is string

Type string

3-1-stringDemo/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

int main(void)
{
	string name = "mtianyan";
	string hobby("football");
	cout << name << endl;
	cout<<hobby << endl;
	system("pause");
	return 0;
}
Copy the code

Note the introduction of String. h, whose namespace is also STD

Multiple ways to initialize a string

string s1;        / / s1 is empty string
string s2("ABC"); // initialize s2 with a string literal;
string s3(s2);    // initialize s3 as a copy of s2.
string s4(n,'c')  // initialize S4 to n copies of the character 'c'. 3 CCC s4 = 'CCC'
Copy the code

Common operations on string

s.empty() // Return true if s is an empty string, false otherwise;
s.size()  Return the number of characters in s
s[n]      // returns the character at position n in s, starting at position 0
s1 + s2   // Concatenate two strings into a new string, returning the newly generated string
s1 = s2   // replace the contents of s1 with a copy of S2;
v1 == v2  // Return true for equality, false otherwisev1 ! = v2// return true for inequality, false otherwise
Copy the code

By means of dots, s is an object

S1 + S2 thinking trap

Pure string concatenation is an illegal operation. Only pure strings and strings, and strings and strings are valid.

Code demo

Because you want to determine if the input is null. Instead of simply using CIN, use getLine

3-1-NameStringDemo/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;


int main(void)
{

	string name;
	cout << "please input your name:";
	getline(cin, name);
	if (name.empty()){
		cout << "input is null" << endl;
		system("pause");
		return 0;
	}
	if (name == "mtianyan")
	{
		cout << "you are a admin" << endl;

	}
	cout << "hello ," + name << endl;
	cout << "your name length is :" << name.size() << endl;
	cout << "your name frist letter is :" << name[0] < <endl;

	system("pause");
	return 0;
}
Copy the code

In c++, getline is used to get input from the external console (when containing possible null input). In general, CIN is better.

Administrator:

Empty name:

Other Common Names

Unit to consolidate

Define a Student class with name and age data members, instantiate a Student object, and print it out as two data members

3-2-StudentClassString/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

/** * Define class: Student * data members: name, age */
class Student
{
public:
	// Define the data member name m_strName and age m_iAge
	string m_strName;
	int m_iAge;
};

int main(a)
{
	// instantiate the Student object stu
	Student stu;
	// Sets the data member of the object
	stu.m_strName = "mtianyan";
	stu.m_iAge = 21;

	// Print the data members of the STu object through cout
	cout << stu.m_strName << "" << stu.m_iAge << endl;
	system("pause");
	return 0;
}
Copy the code

Introduction to C++ property encapsulation

Data encapsulation

Our previous usage was as shown above. But this is not in line with the guiding ideology of object orientation.

Basic idea of object orientation :(take object as center, express program logic by who does what)

  • Translate all the problems into who does what, all the behavior of the object in the program, that is, call member functions to solve the problem.
  • The data members set & get methods are encapsulated by functions.

Benefits of encapsulation: In line with object-oriented thinking, restrictions are placed on parameter conditions in sets (to prevent data from being illegal, such as age 1000)

Data read-only not write (read-only attribute) : Write only get method, not set method.

The number of wheels should be readable and cannot be changed by outsiders.

C code properties encapsulate code demonstrations

Define a Student class with the following information

  • Name: name
  • Gender: gender
  • Credits (Read Only) : Score
  • Study: Study method

4-2-StudentEncapsulation/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;
class Student {
public:

	string getName(a) const 
	{
		return m_strName; 
	}

	void setName(string _name) 
	{ 
		m_strName = _name; 
	}

	string getGender(a)
	{
		return m_strGender;
	}

	void setGender(string val)
	{
		m_strGender = val;
	}

	int getScore(a) {
		return m_iScore;
	}

	void study(int _score) {
		m_iScore += _score; 
	}

	void initScore(a) {
		m_iScore = 0;
	}
private:
	string m_strName;
	string m_strGender;
	int m_iScore;

};

int main(void)
{
	Student stu;
	stu.initScore();
	stu.setName(The Moon Star);
	stu.setGender("Male");
	stu.study(5);
	stu.study(3);

	cout << stu.getName() << "" << stu.getGender() << "" << stu.getScore() << endl;
	
	system("pause");
	return 0;
}
Copy the code

Do not assign an initial value:

Notice that the initial value is assigned. You’ll learn about constructors later, which are specifically used for initialization.

Unit to consolidate

Define a Student class that contains the name as a data member. Use the get and set functions to encapsulate the name as a data member. Instantiate the object with new in the main function and print its related functions.

4-3-StudentHeapInstance/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

/** * Define class: Student * data member: m_strName * Data member encapsulation functions: setName(), getName() */
class Student
{
public:
    // Define the data member wrapper function setName()
    void setName(string _name) 
	{ 
		m_strName = _name; 
	}
    
    
    // Define the data member wrapper function getName()
    string getName(a) const 
	{
		return m_strName; 
	}
    
// Define Student private data member m_strName
private:
	string m_strName;

};

int main(a)
{
    // Instantiate the object using the new keyword
	Student *str = new Student();
    // Sets the data member of the object
	str->setName("mtianyan");
    // Print the data members of the STR object using cout
    cout << str ->getName() << endl;
    // Free the memory of the object STR and empty it
	delete str;
	str = NULL;
	system("pause");
	return 0;
}
Copy the code

Class definitions and inline functions

Inline function keyword: inline

inline void fun(a)
{
	cout << "hello" << endl;
}
Copy the code

  • Ordinary functions find the function body first, and then return the statement calling the function after executing the function content.
  • The inline function inline replaces the function call statement with the function body code and arguments at compile time and executes faster, but only for simple functions.

In-class and out-of-class definitions

  • In-class definition refers to the function body that defines member functions within a class (preferably compiled inline)

Inline is not written, but is compiled inline first

  • Out-of-class definition refers to defining how a function works outside the class and then declaring it inside the class.

Out-of-class definitions fall into two categories:

  • Out-of-class definition: A member function is defined outside the class, but it is defined in the same file as the class
  • Out of file class definition: member function

Example of definition outside the same file class: car.cpp

To indicate that this is a member function of car: car::

The same file class definition is commandos, sub-file class definition is the regular army.

Almost all c++ programs are defined outside the file class by professional programmers.

Subfile class definition

A.h header file with the same name as the class. Must include. H files and use car::

Out-of-class definition code demo

Requirements:

5-2-1-OutClassDefine1/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>

using namespace std;
class Teacher {
public:
	void setName(string name);
	string getName(a);

	void setGender(std: :string val);
	string getGender(a);

	void setAge(int _age);
	int getAge(a);

	void teach(a);
private:
	string m_strName;
	string m_strGender;
	int m_iAge;
};

string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
string Teacher::getGender() 
{
 return m_strGender;
}
void Teacher::setGender(string val) 
{
 m_strGender = val; 
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
void Teacher::teach() {
	cout << "Class now." << endl;
};
int main(void)
{
	Teacher teacher;
	teacher.setAge(21);
	teacher.setName("mtianyan");
	teacher.setGender("Male");
	cout << teacher.getName() << "" << teacher.getGender() << "" << teacher.getAge() << endl;
	teacher.teach();
	system("pause");
	return 0;
}
Copy the code

The implementation is defined outside the file class.

5-2-2-MultipleFilesOutClassDefine/main.cpp

In the solution, right-click the header file and add the new item: header file: teach. h Right-click the source file and add the new item: CPP: teach.cpp

Teacher.h stores only class declarations

#include <string>
using namespace std;

class Teacher {
public:
	void setName(string name);
	string getName(a);

	void setGender(std: :string val);
	string getGender(a);

	void setAge(int _age);
	int getAge(a);

	void teach(a);
private:
	string m_strName;
	string m_strGender;
	int m_iAge;
};
Copy the code

Teach. CPP: Stores only definitions of out-of-class methods

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;

string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
string Teacher::getGender() 
{
	return m_strGender;
}
void Teacher::setGender(string val) 
{ 
	m_strGender = val; 
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
void Teacher::teach() {
	cout << "Class now." << endl;
};
Copy the code

Main. CPP holds instantiations of classes and other programs as well as the main entry

#include <stdlib.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;

int main(void)
{
	Teacher teacher;
	teacher.setAge(21);
	teacher.setName("mtianyanMultiple");
	teacher.setGender("Male");
	cout << teacher.getName() << "" << teacher.getGender() << "" << teacher.getAge() << endl;
	teacher.teach();
	system("pause");
	return 0;
}
Copy the code

The header file for main. CPP is:

#include <stdlib.h>
#include <iostream>
#include "Teacher.h"
using namespace std;
Copy the code

Head to the Teacher. H

#include <string>
using namespace std;
Copy the code

The header of tercher.cpp is:

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;
Copy the code

Note: Do not<string>written<string.h>

C++ constructor tutorial

  • How are instantiated objects stored in memory?
  • How is the code stored in the class?
  • How does data relate to code?

Object structure

Memory partition

  • The stack area:int x=0; int*p=NULL;Memory is managed by the system.
  • The heap area:int *p = new int[20]; new & delete
  • Global area: stores global and static variables
  • The constant area:string str = "hello";
  • Code area: stores the compiled binary code

Define a car class that does not consume stack or heap memory until the class is instantiated. But when it instantiates car1, car2,car3. Each object creates an area of memory on the stack to store its own data. Different variables take up different amounts of memory.

There is only one code in the code area.

Object initialization

Tank battle, the game starts to initialize the tank position.

There are two types of object initialization:

  • There is one and only one initialization
  • Class according to conditions

For once and only initializations:

  • Consider: How do initializers avoid misoperations?

For example, we write code that forgets to call the initialization function and calls the initialization function repeatedly.

Constructor rules and features:

  • The constructor is called automatically when the object is instantiated; All you need to do is write the initialization code inside the constructor.

Constructors are not called when the object is instantiated and are called only once

  • The constructor has the same name as the class;
  • The constructor returns no value;
  • Constructors can be overloaded; Follow the rules for overloaded functions.
  • Instantiate an object with only one constructor;
  • When the user does not define a constructor, the compiler automatically generates a constructor that does nothing in it.

No parameter constructor

class Student
{
public:
	Student(){
		m_strName = "jim";
	} // Same as the class name, no return value.
private:
	string m_strName;
}
Copy the code

Has parameter constructors

class Student
{
public:
	Student(string name){
		m_strName = name;
	}
private:
	string m_strName;
}
Copy the code

Overloaded constructor

class Student
{
public:
	Student(){
		m_strName = "jim";
	}
	Student(string name){
		m_strName = name;
	}// Overload: The number of arguments is different, the type of arguments is different, and the order of calling the arguments is different.
private:
	string m_strName;
}
Copy the code

C++ constructor code demo

	Teacher();
	Teacher(string name, int age=20);
Copy the code

Such computers are distinguishable, but if name is also given a default value. It will not compile. Warning that overloaded function calls are not explicit. Two cannot coexist, but can exist alone.

6-2-ConstructorFunction

Teacher.h

#include <string>
using namespace std;

class Teacher {
public:
	Teacher();
	Teacher(string name, int age=20);
	void setName(string name);
	string getName(a);
	void setAge(int _age);
	int getAge(a);
	void teach(a);
private:
	string m_strName;
	int m_iAge;
};
Copy the code

teacher.cpp

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;

Teacher::Teacher() {
	m_strName = "jim";
	m_iAge = 5;
	cout << "Teacher()" << endl;
}

Teacher::Teacher(string name, int age) {
	m_strName = name;
	m_iAge = age;
	cout << "Teacher(string name, int age)" << endl;
}

string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
void Teacher::teach() {
	cout << "Class now." << endl;
};
Copy the code

main.cpp

#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;

int main(void)
{
	Teacher teacher; // Parameterless instantiation. This works because we didn't assign default values to all the parameters.
	Teacher t2("merry".15);// There are arguments instantiated
	Teacher t3("james");The constructor has a default value of 20
	cout << teacher.getName() << "" << teacher.getAge() << endl;
	cout << t2.getName() << "" << t2.getAge() << endl;
	cout << t3.getName() << "" << t3.getAge() << endl;
	teacher.teach();
	system("pause");
	return 0;
}
Copy the code

Constructors can also assign default values to arguments in addition to overloading. When not called, compilation will pass.

Default constructor

One of the features of instantiating objects, whether from the heap or stack, is that no arguments are passed.

Such constructors can be defined as shown in the figure above and take no arguments themselves.

Or with the default values of all parameters.

  • Constructors that do not pass arguments when instantiated are called default constructors. Both of the above (and the code below) are default constructors.
Student(){}
Student(string name = "jim");
Copy the code

The constructor initializes the list

class Student
{
public:
	Student():m_strName("jim"),m_iAge(10) {}// The constructor initializer list is initialized
private:
	string m_strName;
	int m_iAge;

}
Copy the code

Constructors are separated by a colon and, for multiple data member initializations, by commas. We use parentheses for assignments.

Initializing list properties

  • The initializer list is executed before the constructor
  • Initializer lists can only be used for constructors
  • Initializer lists can initialize multiple data members at the same time, and are efficient and fast.

The need to initialize the list:

Consider: what’s the use of initializing a list when it looks like it could be done by a constructor?

Here are some examples.

Computes a circle, where PI is a constant, so it is const.

class Circle
{
public:
	Circle(){m_dPi=3.14} // Error, assign constant
private:
	const double m_dPi;
}
Copy the code

Unable to assign initial values to our static member variables in the constructor, solution: assign initial values in the initializer list.

class Circle
{
public:
	Circle():m_dPi(3.14) {}// Correct, use the initializer list
private:
	const double m_dPi;
}
Copy the code

C++ initializes list encoding

Defines a default constructor with parameters that initializes data using an initializer list.

6-5-ParameterConstructorFunctionInitList

Teacher.h

#include <string>
using namespace std;

class Teacher {
public:
	Teacher(string name ="hi".int age=1.int m =100); // Takes a default constructor
	void setName(string name);
	string getName(a);

	void setAge(int _age);
	int getAge(a);

	int getMax(a);
	void setMax(int m_iMax);
private:
	string m_strName;
	int m_iAge;
	const int m_iMax;

};
Copy the code

Teacher.cpp

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;

Teacher::Teacher(string name, int age ,int m):m_strName(name),m_iAge(age),m_iMax(m)
{
	cout << "Teacher(string name, int age)" << endl;
}

string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
int Teacher::getMax() {
	return m_iMax;
}
void Teacher::setMax(int m_iMax) {
	m_iMax = m_iMax;
}
Copy the code

main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;

int main(void)
{
	Teacher teacher("merry".12.150);
	cout << teacher.getName() << "" << teacher.getAge() <<""<<teacher.getMax()<< endl;
	system("pause");
	return 0;
}
Copy the code

A class may not have a default constructor and may instantiate objects with other constructors. When a constructor is declared with a default value, it does not need to be defined with a default value.

Constants that are not initialized in the initializer list are prompted to be initialized in the initializer list

C++ copy constructor

Above, this is the Student class we defined

When used.

int main(a)
{
	Student stu1;
	Student stu2 =stu1;
	Student stu3(stu1);
	return 0;
}
Copy the code

Three objects are instantiated, but the above code executes the code inside the constructor only once.

The triple instantiation calls the constructor, but we don’t define it ourselves, we copy the constructor.

Instantiating an object must call a constructor, but code like the one above will use a copy constructor instead of the one we defined.

Copy constructor:

Definition format: class name (const class name & variable name)

Student(){
	m_strName = "jim";
}
Student(const Student& stu){

}
Copy the code

Pass in a reference.

  • If there is no custom copy constructor, the system automatically generates a default copy constructor
  • When using direct initialization (stu3(stu1);) or copy initialization (stu2 =stu1;The copy constructor is automatically called when an object is instantiated

Constructor summary:

  • No-argument constructor: must be the default constructor

  • Parameterized constructors:

    - Parameter with default value. If the arguments have default values, then it will be the default constructor - the arguments have no default valuesCopy the code

Functions automatically generated by the system:

  • Ordinary constructor
  • Copy constructor

Once we define ourselves, the system won’t regenerate.

Initialization list:

  • Ordinary constructor
  • Copy constructor

C++ copy constructor code demo

6-8-CopyConstructorFunction

Teacher.h

#include <string>
using namespace std;

class Teacher {
public:
	Teacher(string name ="mtianyan".int age=21.int m =100);
	Teacher(const Teacher& tea); // Copy the constructor
	void setName(string name);
	string getName(a);
	void setAge(int _age);
	int getAge(a);
private:
	string m_strName;
	int m_iAge;
};
Copy the code

teacher.cpp

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;

Teacher::Teacher(string name, int age ,int m):m_strName(name),m_iAge(age)
{
	cout << "Teacher(string name, int age)" << endl;
}
Teacher::Teacher(const Teacher& tea) {
	cout << "Teacher(const Teacher &tea)" << endl;
}
string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
Copy the code

main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;

void test(Teacher t) {}int main(void)
{
	Teacher teacher;
	Teacher t2 = teacher;
	Teacher t3(t2);  // if t2 or teacher is used, only the copy constructor is called
	test(teacher); // called when the function uses an instantiated object.
	cout << teacher.getName() << "" << teacher.getAge() << endl;
	system("pause");
	return 0;
}
Copy the code

The copy constructor is called when a function takes an instantiated object as an argument. If the test ()

The arguments to the copy constructor are deterministic and cannot be overridden

The destructor

The constructor is the first cry an object makes when it enters the world. The destructor is the last sigh an object makes when it leaves the world.

The destructor is called automatically when the object is destroyed, returning system resources:

Definition format:

~ Class name () // Takes no argumentsCopy the code
class Student
{
public:
	Student(){cout << "Student" << endl; } ~Student(){cout << "~Student" << endl;}
}
Copy the code

Destructors are not allowed to take any arguments.

Destructor value:

If we use Pointers when defining data, we use Pointers to point to memory allocated in the heap (new). We want to free this memory when the object is destroyed, and the best time to free this memory is before the object is destroyed.

class Student
{
public:
	Student(){m_pName = new char[20]; } ~Student(){delete[]m_pName; }private:
	char *m_pName;
}
Copy the code
  • Destructors have no return value, no arguments and cannot be overloaded
  • If there is no custom destructor, the system automatically generates it
  • The destructor is called automatically when the object is destroyed

Object’s life course:

  1. Application memory
  2. Initialize the list (when other values are uncertain)
  3. The constructor
  4. Participate in operation
  5. The destructor
  6. Free memory

C++ destructor code demonstration

The destructor is called immediately after you press Enter

6-11-DestructorFunction

Teacher.h

#include <string>
using namespace std;

class Teacher {
public:
	Teacher(string name ="mtianyan".int age=21.int m =100); / / structure
	Teacher(const Teacher &tea); // Copy construct
	~Teacher(); / / destructor
	void setName(string name);
	string getName(a);
	void setAge(int _age);
	int getAge(a);
private:
	string m_strName;
	int m_iAge;

};
Copy the code

Teacher.cpp

#include "Teacher.h"
#include <iostream>
#include <string>
using namespace std;

Teacher::Teacher(string name, int age ,int m):m_strName(name),m_iAge(age)
{
	cout << "Teacher(string name, int age)" << endl;
}
Teacher::Teacher(const Teacher &tea) {
	cout << "Teacher(const Teacher &tea)" << endl;
}
Teacher::~Teacher() {
	cout << "~Teacher()" << endl;
}
string Teacher::getName()
{
	return m_strName;
}
void Teacher::setName(string name)
{
	m_strName = name;
}
int Teacher::getAge() {
	return m_iAge;
}
void Teacher::setAge(int _age) {
	m_iAge = _age;
}
Copy the code

main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
#include "Teacher.h"
using namespace std;

void test(Teacher t) {}int main(void)
{
	Teacher t1;
	Teacher t2(t1);
	Teacher *p = new Teacher();
	delete p;
	p = NULL;
	system("pause");
	return 0;
}
Copy the code

At the moment you press Enter, you see the following two lines of output. This is where we call the destructor t1 t2 on destruction.

~Teacher()
Copy the code

Destructors are called automatically when objects in the stack are destroyed.

conclusion

Comb through the previous learned & reveal the plot behind

Expand around classes and objects.

A class consists of member functions and data members. Worrying about your class having the same name as someone else, you can define namespaces on your class.

Data member:

Common data member,(common data type) int, char, char[], string; Initialize the list (const member); Static data member; Members of the object

Member functions:

Encapsulate data members, attribute encapsulates functions (get,set); General function function; Special functions: constructors (copy constructors – default constructors, depending on arguments); Destructor.

Member functions (parameter defaults; Function overloading; Reference; const;)

Object instantiation (heap instantiation, stack instantiation)

Can an object be a reference? Can objects be decorated with const?

  • How to identify data members in member functions.
  • How do multiple objects share data
  • Object member is initialized

Comprehensive exercises:

Define a Student class with a name as a data member, define a no-argument constructor, a parameterized constructor, a copy constructor, a destructor, and a function that encapsulates the name, instantiate the Student object in the main function, and access the related functions to observe the result.

7-2-StudentDemo/main.cpp

#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;
/** * Define class: Student * Data member: m_strName * No argument constructor: Student() * Argument constructor: Student(string _name) * copy constructor: Student(const Student& stu) * destructor: ~Student() * data member functions: setName(string _name), getName() */
class Student {
public:
	Student() {
		m_strName = "";
	};
	Student(string _name) {
		m_strName = _name;
	};
	Student(const Student& stu) {

	};
	~Student() {

	};
	void setName(string _name) {
		m_strName = _name;
	};
	string getName(a) {
		return m_strName;
	};
private:
	string m_strName;
};

int main(void)
{
	// Instantiate the object *stu with new
	Student *stu = new Student();
	// Change the data member of the object to "mtianyan"
	stu->setName("mtianyan");
	// Prints the data member of the object
	cout << stu->getName() << endl;
	delete stu;
	stu = NULL;
	system("pause");
	return 0;
}
Copy the code

Note that objects instantiated in new do not forget delete and pointer null.