Re-pick C + + initialization

Source: Internet
Author: User

First, initialize

Creating an object is giving him a specific value, called initialization. There are several initialization methods in C + +:

int a = 1;//of course int a=  (1) is also possible. Int a (1); int a={1};int a{1};/* initialization with "{}" is the standard of c++11, which is suitable for    Also applies to initialization of custom objects and assignment in some cases .*/class a{private:    int a;     Int b;public:    a (int a,int b) {         this->a=a;        this->b=b;         cout<< "Hello base a" <<endl;         cout<<a<< '-' <<b<<endl;    }    virtual  void show () {        cout<< "Hello my name  is a "<<endl;    }}; (A a); a a{1,2}; a a={1,2};a={3,4};//above are all possible, but there must be a corresponding constructor. It is important to note that A a is normally used, and the a a{1,2}; two formulations are generic. However, if you provide a list of the initial element values, there is a difference between the two. SeeArticle III 

Second, default initialization

If you define a variable that does not display the specified initial value, it will be initialized by default, the global base type variable and static static local variable will be initialized, the class and struct will call its constructor for initialization, the value of the local automatic variable is unknown, and in some cases may cause a program exception.

Iii. c++11 list initialization and in-class initialization

Assigning a value to a member of a class previously within a class is not allowed, and in-class initialization can be done in c++11

Class A{private:int a=0; Stirng str= ' fine ';} This approach is legal in c++11 (-STD=C++11), which is initialized by default when no initial value is provided.

Initialization list:

There are a lot of differences between the following two usages of vector objects.

Vector<int> v1 (10,1);//contains 10 elements with a default value of 1 vector<int> v2{10,1};//contains 2 elements, the default value is 10 and 1


To regain the initialization of C + +

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.