Notes for collection Initialization

Source: Internet
Author: User

A set is the aggregate of multiple things, including arrays, struct, and classes.

For the internal type array, we can define it like this

 

Int a [5] = {1, 2, 3, 4, 5 };

Int B [5] = {0 };

Int c [] = {1, 2, 3, 4, 5 };

 

For a struct, we can also use the {} initial method as follows:

 

Struct X

{

Int I;

Float f;

};

X x1 = {1, 1.1 };

X x2 [3] = {1, 1.1}, {2, 2.2} // The third object is initialized to 0.

 

However, if our class has private members, or all the member variables are public members but there are constructors, we cannot simply use the {} initialization method, all initialization work must be completed by the constructor.

 

# Include <iostream>

Using namespace std;

Class X

{

Public:

Int I;

Float f;

X () {cout <"default constructor" <endl ;}

X (int e, float q): I (e), f (q) {cout <"constructor" <endl ;}

 

};

Int main ()

{

// X a = {0, 0}; // compilation error, because the constructor must be called before Initialization

X B [2]; // use the default constructor for initialization

X c [3] = {X (1, 1.1), X (2, 2.2)}; // use a General constructor for initialization

Return 1;

}

Running result:

Default constructor

Default constructor

Constructor

Constructor

Default constructor

 

By identifying the differences between classes and struct initialization methods, we can think that classes are not a set in a strict sense.

 

Author: yucan1001

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.