Constructors In the struct and class have the same functions, but there are also many differences, and these differences are very important. I. first look at the constructor in the class. /*
* Created by sharpdevelop.
* User: noo
* Date: 2009-8-26
* Time: 12: 30
*
* Class constructor.
* (1) When no constructor is written to the class, the class will call the non-argument constructor of the parent class system. object by default during class instantiation.
* (2) when only the constructor with parameters is written in the class, only the overloaded constructor can be called during class instantiation, if you continue to call a constructor without parameters, an error is returned.
*/
Using system;
Class constructa
{
Public void output ()
{
Console. writeline ("success ");
}
}
Class constructb
{
Public constructb (int)
{
Console. writeline ();
}
Public void output ()
{
Console. writeline ("success ");
}
}
Class Test
{
Static void main ()
{
Constructa CA = new constructa ();
CA. Output ();
// Constructb cb = new constructb (); // call error. The "constructb" method does not use the overload of "0" parameters.
// CB. Output ();
Constructb cb = new constructb (5 );
CB. Output ();
}
}
Ii. Next let's look at the constructor In the struct. /*
* Created by sharpdevelop.
* User: noo
* Date: 2009-8-26
* Time: 12: 44
*
* Constructor of struct
* (1) constructor without parameters cannot be written in the struct. Only constructor with parameters can be written. The constructor of the same type is different.
* (2) when there is only a constructor with parameters in the struct, you can call a constructor without parameters to instantiate the struct. This type of constructor is also different.
*
*/
Using system;
Struct constructc
{
// Constructc () // The structure cannot contain explicit non-parameter constructor. This is the default constructor of the struct. Unlike classes, this cannot be rewritten.
//{
// Console. writeline ("fail ");
//}
Public void output ()
{
Console. writeline ("success ");
}
}
Struct constructd
{
Public constructd (int A) // only the constructors with parameters of the struct can be reloaded here.
{
Console. writeline ();
}
Public void output ()
{
Console. writeline ("success ");
}
}
Class Test
{
Static void main ()
{
Constructc cc = new constructc (); // call the default constructor of the struct.
Cc. Output ();
Constructd Cd = new constructd (); // This instantiation method is also correct.
CD. Output ();
Constructd CD2 = new constructd (5); // call the constructor with parameters of the struct.
}
}
Through the comparison above, we believe you can understand the similarities and differences between struct and constructor in the class.