const static data members 초기화 하기

막상 쓰려니 헷갈려서.. 책을 찾아서 정리함.

//static data member들은모든block의밖에서define 되어야한다
//모든block의밖에서define되는static data memeber들은따로초기화값을주지않으면
//자동으로0으로초기화된다.

class Widget

{

        static int n;          //declaration

};

int Widget::n = 0;            //definition

 

 

//const data member들은constructor's initialization section에서초기화가되어야한다.

//member initialization list

class Widget

{

public:

        Widget() : n( 0 ) { }

private:

        const int n;           //const data member

};

 

//const static data member들은integral type일경우, in-class initialization이허용되고,

//non-integral type일경우, class 밖에서초기화되어야한다.

#include <string>

class Widget

{

public:

        //..

private:

        static const int MAX = 512;           //definition

        static const char flag = 'a';         //also a defintion

        static const std::string msg;         //non-integral type; must be defined outside the class body

};

const std::string Widget::msg = "hello";


* 참고  

Integral type : bool, char, wchar_t, signed char, short int, int, long int, unsigned char, unsigned short int, unsigned int, unsigned long int
Floating-point type : float, double, long double

댓글

Designed by JB FACTORY