The meaning of the constructor:
A shortcut to implement class member initialization.
Usage Restrictions:
1. Same as the class name;
2. No return type, void can not;
3. Most of its access rights are public, and if used for its derived classes, it can be protect;
Call Mechanism:
When defining a class object, the constructor is called. If there is no explicit declaration, the system calls the missing default constructor. If there are multiple constructors, you need to explicitly specify which one to call when you define the class object.
Declaration Template for Constructors:
Classname::classname ()
{
...;
}
Destructors:
At the end of the object's lifetime, the space allocated by the system to the object is freed, that is, an object is undone. However, it is important to note that new objects are not automatically freed and need to call their inverse operator delete.
Usage Restrictions:
1. The function name must be the same as the class name and precede it with the character "~";
2. Cannot have any parameters, cannot have return value, do not specify function type;
3. In a class, only one destructor can be defined, and the destructor does not allow overloading;
4. Destructors are automatically called by the system when an object is undone.
Declaration Template for Destructors:
Classname::~classname ()
{
...;
}
An example of a constructor and destructor:
#include <iostream>
class Simpleclass
{
private:
float x, y;
Public:
float m,n;
void SetXY (float,float);
void Getxy ();
Simpleclass (float,float);
~simpleclass ();
};
Simpleclass::~simpleclass ()
{
std::cout << "Goodbye,crue world!" << Std::endl;
}
Simpleclass::simpleclass (float a,float b)
{
x = A;
y = b;
}
void Simpleclass::setxy (float a,float b)
{
x = A;
y = b;
}
void Simpleclass::getxy (void)
{
std:: cout << x << ' \ t ' << y << std::endl;
}
int main (void)
{
simpleclass cls1 (3.0,6.0);
CLS1.M = ten;
CLS1.N =;
Cls1.getxy ();
Cls1.setxy (2.0,5.0);
Cls1.getxy ();
return 0;
}
Compile run:
root@se7en-lifebook-lh531:~/learn/cpp_program# g++ This.cpp-o this
root@se7en-lifebook-lh531:~/learn/cpp_ program#./this
3 6
2 5
goodbye,crue world!