zoukankan      html  css  js  c++  java
  • Initialization of data members

      In C++, class variables are initialized in the same order as they appear in the class declaration.

      Consider the below code.

     1 #include<iostream>
     2 
     3 using namespace std;
     4 
     5 class Test 
     6 {
     7 private:    
     8     int y;
     9     int x;    
    10 public:
    11     Test() : x(10), y(x + 10) 
    12     {
    13     }
    14     void print();
    15 };
    16 
    17 void Test::print()
    18 { 
    19     cout<<"x = "<<x<<" y = "<<y; 
    20 }
    21 
    22 int main()
    23 {
    24     Test t;
    25     t.print();
    26     getchar();
    27     return 0;    
    28 }

      The program prints correct value of x, but some garbage value for y, because y is initialized before x as it appears before in the class declaration.

      So one of the following two versions can be used to avoid the problem in above code.

     1 // First: Change the order of declaration.
     2 class Test 
     3 {
     4 private:    
     5     int x;    
     6     int y;
     7 public:
     8     Test() : x(10), y(x + 10) 
     9     {
    10     }
    11     void print();
    12 };
    13 
    14 // Second: Change the order of initialization.
    15 class Test 
    16 {
    17 private:    
    18     int y;
    19     int x;    
    20 public:
    21     Test() : x(y-10), y(20) 
    22     {
    23     }
    24     void print();
    25 };

      Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

      转载请注明:http://www.cnblogs.com/iloveyouforever/

      2013-11-26  10:23:29

  • 相关阅读:
    第八章 路由器交换机及其操作系统的介绍
    k-Tree DP计数
    Drop Voicing 最长升序
    高精度
    1196D2
    C
    POJ 3974 马拉车
    2020.8.1第二十六天
    2020.7.31第二十五天
    每日日报
  • 原文地址:https://www.cnblogs.com/iloveyouforever/p/3442772.html
Copyright © 2011-2022 走看看