I. Instantiating an object from a stack
We first define a class whose name is TV, which includes two member variables and two member functions.
class // define a TV's class TV {public: char name[// defines the properties of the class, an array int type; void // defining member functions void power ();}
The following begins instantiating an object from the stack
If you define an object, we write an object TV behind the class TV;
If you define an array of objects, we write the array object behind the class TV tv[20], and 20 is the element required by the array.
int Main (void) { TV TV; // defining an Object TV tv[]; // defining an array of objects return 0 ;}
Example:
#include <iostream>#include<stdlib.h>using namespacestd;classCoordinate//define a class coordinate (coordinates){ Public://Access Qualifier intX//define a member variable x (coordinate x) intY//define a member function y (coordinate y) voidPrintx ()//defines a member function Printx (), which is the function of the output x value{cout<< x <<Endl; } voidPrinty ()//defines a member function Printy (), which is the function of the output Y value{cout<< y <<Endl; }};intMainvoid){ //instantiate a class in a stackcoordinate coor;//coor is an instantiated object defined in the stackCoor.x =Ten;//accessing a data member, assigning a value to a member variable xCOOR.Y = -; Coor.printx ();//Calling member functionscoor.printy ();}Ii. instantiating an object from a heap
We first define a class whose name is TV, which includes two member variables and two member functions.
class // define a TV's class TV {public: char name[// defines the properties of the class, an array int type; void // defining member functions void power ();}
The following begins instantiating an object from the stack
When instantiating an object in a heap, we first request a piece of memory to give the memory to the instantiated object or group of objects;
After use, we will release the memory.
int Main (void) { new// Request an object in the heap new tv[ - // request an Array object in the heap, 20 variables Delete p; // frees the memory of an object Delete // frees an array of memory return 0 ;}
Example:
#include <iostream>#include<stdlib.h>using namespacestd;classCoordinate//define a class coordinate (coordinates){ Public://Access Qualifier intX//define a member variable x (coordinate x) intY//define a member function y (coordinate y) voidPrintx ()//defines a member function Printx (), which is the function of the output x value{cout<< x <<Endl; } voidPrinty ()//defines a member function Printy (), which is the function of the output Y value{cout<< y <<Endl; }};intMainvoid){ //instantiate a class in a heapCoordinate *p =Newcoordinate (); P->x = -;//assign a value to x in the form of a pointerP->y = $; P->printx ();//calling a function as a pointerP->Printy (); System ("Pause"); return 0;}
C + + Instantiation Object