C ++ const member Initialization

Source: Internet
Author: User

Like any other member, a Const member appears in three positions: global scope, common function, and class.
See the test code for the front:
1 # include "stdafx. h"
2 # include <iostream>
3
4 using namespace std;
5
6 class
7 {
8 public:
9 const int j;
10 // const int k = 3;
11 const static int I;
12 };
13
14 // const static int A: I = 0;
15 const int A: I = 1;
16
17 // const int j;
18 int _ tmain (int argc, _ TCHAR * argv [])
19 {
20 // const int I;
21 cout <A: I <endl;
22 return 0;
23}

 

The following conclusions are drawn:
1. const constants must be initialized during global scope Declaration; otherwise, they cannot be compiled.
2. const constants are the same in common functions (the main function here) and must be initialized at the time of declaration.
3. In the definition break of the class (A here), we can see from the const constant j that it can be declared without initialization. For special reasons, we can see from the const constant k that we cannot start the statement in the class definition body (for the reason, see 5 ).
4. Similarly, const static can be declared in the class definition body and initialized outside the class (here const static int I ). However, note that I can be initialized in the class definition body.
5. C ++ stipulates that only the "const static integer member" can be initialized in the class definition body.

 

From Yao H. Wang

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.