20th constructor and destructor
Constructor: A special member function. It is mainly used to allocate storage spaces for objects.
To initialize data for data members;
1. The name of the constructor must be the same as that of the class;
2. the constructor does not return a type. It can contain parameters or not.
3. The main function of the constructor is to complete class initialization.
4. When creating a new object of a class (using the new keyword), the system automatically calls the class
The constructor to initialize a new object;
Destructor: A special member function called when an object is destroyed.
1. When an object meets the destruction condition, the Destructor is automatically called and cannot explicitly
It is called;
2. Generally, you do not need to write your own destructor. But sometimes it must be written, that is, you
You use unmanaged resources. For example, when you use API functions
Resources.
Code:
Namespace First {
Public partial class Form1: Form {
Public Form1 (){
InitializeComponent ();
}
Private void Form1_Load (object sender, EventArgs e ){
// A a = new ();
// A a = new A (1 );
B B = new B ();
B = null;
GC. Collect ();
GC. WaitForPendingFinalizers ();
}
}
// Customize Class
// Constructor
Public class {
// Member variable
Int num;
// Constructor
Public A () {MessageBox. Show ("No parameter constructor is called !! ");}
Public A (int I ){
Num = I;
MessageBox. Show ("Call the valid parameter constructor !! ");
}
}
Class B {
~ B (){
MessageBox. Show ("called destructor ");
}
}
}
21st static methods static variables
Static shared data
We use Math
MessageBox. Show
Code:Private void Form1_Load (object sender, EventArgs e ){
/*
Int renShu = BanJi. NumberOfStudents; // obtain static member variables
This. textBox1.Text = renShu. ToString ();
//*/
/*
BanJi theBanJi1 = new BanJi ();
BanJi theBanJi2 = new BanJi ();
TheBanJi1.AndBoy ();
TheBanJi2.AndBoy ();
Int renShu = BanJi. NumberOfStudents; // obtain static member variables
This. textBox1.Text = renShu. ToString ();
//*/
/*
BanJi theBanJi1 = new BanJi ();
BanJi theBanJi2 = new BanJi ();
TheBanJi1.AndBoy ();
TheBanJi2.AndBoy ();
BanJi. ResetNumberOfStudent ();
Int renShu = BanJi. NumberOfStudents; // obtain static member variables
This. textBox1.Text = renShu. ToString ();
//*/
MessageBox. Show ("PI value:" + Math. PI. ToString ());
MessageBox. Show ("sin5 value:" + Math. Sin (5). ToString ());
}
}
Public class BanJi {
// Static member variable
Public static int NumberOfStudents = 0;
// Static member functions
Public static void ResetNumberOfStudent () {NumberOfStudents = 0 ;}
// Non-static member functions
Public void AndGirl () {NumberOfStudents ++ ;}
Public void AndBoy () {NumberOfStudents ++ ;}
}
Static class CompanyInfo {
Public static string GetCompanyName () {return "cosmic cigarettes ";}
Public static string GetCompanyAddress () {return "Beijing Capital ";}
}
}