天天看點

如何初始化類的const成員變量?

如何初始化類的const成員變量?

------------------------------------------------------------------------------------

一、必須在構造函數中初始化const成員變量。

frank@userver:~/project/test/const-test/const4_cpp$ 

frank@userver:~/project/test/const-test/const4_cpp$ cat const.h -n 

     1  #ifndef CONST_H

     2  #define CONST_H

     3

     4  #include<iostream>

     5  using std::cout;

     6  using std::endl;

     7

     8  class TestType{

     9      const int m_const;

    10  public:

    11      TestType(int dat = 0) {}

    12      void Show()const{

    13          cout << "this=" << this << ", ";

    14          cout << "m_const:(" << &m_const << ", " << m_const << ")\n";

    15      }

    16  };

    17

    18  #endif // #ifndef CONST_H

frank@userver:~/project/test/const-test/const4_cpp$ cat main.cpp -n

     1  #include "const.h"

     2

     3  int main(){

     4      cout << __func__ << endl;

     5      TestType obj(4);

     6      obj.Show();

     7  }

frank@userver:~/project/test/const-test/const4_cpp$ g++ main.cpp 

In file included from main.cpp:1:0:

const.h: In constructor ‘TestType::TestType(int)’:

const.h:11:5: error: uninitialized member ‘TestType::m_const’ with ‘const’ type ‘const int’ [-fpermissive]

     TestType(int dat = 0) {}

     ^

二、不能在構造函數體中對const成員變量指派。

frank@userver:~/project/test/const-test/const4_cpp$ cat const.h  -n

    11      TestType(int dat = 0) { m_const = dat; }

     TestType(int dat = 0) { m_const = dat; }

const.h:11:37: error: assignment of read-only member ‘TestType::m_const’

                                     ^

三、隻能在構造函數初始化清單中初始化const成員變量。每個對象都有一個m_const。

frank@userver:~/project/test/const-test/const4_cpp$ cat const.h -n

    11      TestType(int dat = 0) : m_const(dat) {}

frank@userver:~/project/test/const-test/const4_cpp$ ./a.out 

main

this=0x7fff7ab7d960, m_const:(0x7fff7ab7d960, 4)

frank@userver:~/project/test/const-test/const4_cpp$

      本文轉自FrankNie0101 51CTO部落格,原文連結:http://blog.51cto.com/frankniefaquan/1936646,如需轉載請自行聯系原作者

繼續閱讀