C + + 's constructor learning

Source: Internet
Author: User

#include <stdio.h>

Class Test
{
Private
int i;
Int J;
int k;
Public:
void Initialize ()
{
i=0;
J=1;
I=p;
}

void print ()
{
printf ("i=%d,j=%d,k=%d", i,j,k);
}

}; Semicolons are critical

int main ()
{
Test T1;
T1.initialize (); constructor function
T1.print ();
return 0;
}

Using constructors

#include <stdio.h>

Class Test
{
Private
int i;
Int J;
int k;
Public:
Test (int v)////is the same as the class name
{////constructor definition can have parameter cannot have return type
No return type is different from return type void
I=j=k=v;
}

void print ()
{
printf ("i=%d, j=%d, k=%d \ n", i,j,k);
}

}; Semicolons are critical

int main ()
{
Test T1 (1); Automatically call constructors
Test t2=2; constructor function
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;
}

C + + constructor learning

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.