Constructor learning and constructor learning in c ++

Source: Internet
Author: User

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;
}

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.