Constructor learning and constructor learning in c ++
# Include <stdio. h>
Class Test
{
Private:
Int I;
Int j;
Int k;
Public:
Void initialize ()
{
I = 0;
J = 1;
K = 2;
}
Void print ()
{
Printf ("I = % d, j = % d, k = % d", I, j, k );
}
}; // The semicolon is critical.
Int main ()
{
Test t1;
T1.initialize (); // Constructor
T1.print ();
Return 0;
}
Use constructors
# Include <stdio. h>
Class Test
{
Private:
Int I;
Int j;
Int k;
Public:
Test (int v) // same as the class name
{//// When the constructor is defined, there can be parameters and no return type.
/// No return type is different from the return type void
I = j = k = v;
}
Void print ()
{
Printf ("I = % d, j = % d, k = % d \ n", I, j, k );
}
}; // The semicolon is critical.
Int main ()
{
Test t1 (1); // automatically call the constructor
Test t2 = 2; // Constructor
Test t3 = Test (3 );
T1.print ();
T2.print ();
T3.print ();
Test TA [3] = {Test (1), Test (2), Test (3 )};
For (int I = 0; I <3; I ++)
{
TA [I]. print ();
}
Return 0;
}