const

language/C/C++ 2012. 5. 21. 16:11

void main(void)

{

    const int a = 1;    // a에 대해서 상수로 보호

    //a = 3;        // Compile Error C3892: 'a' : const인 변수에 할당할 수 없습니다.

 

    int const a2 = 1;   // a2에 대해서 상수로 보호

    //a2 = 3;       // Compile Error C3892: 'a2' : const인 변수에 할당할 수 없습니다.

 

    const int *b = NULL;    // *b에 대해서 상수로 보호

    b = &a;

    //*b = 1;       // Compile Error C3892: 'b' : const인 변수에 할당할 수 없습니다.

 

    int const *c = NULL;    // *c에 대해서 상수로 보호

    c = &a;

    //*c = 1;       // Compile Error C3892: 'c' : const인 변수에 할당할 수 없습니다.

 

    int aa = 2;


    int* const d = &aa;     // d에 대해서 상수로 보호

    //d = &aa;      // Compile error C3892: 'd' : const인 변수에 할당할 수 없습니다.

    *d = 3;

 

    const int* const e = &aa;   // *e와 e에 대해서 상수로 보호

    //e = &aa;      // Compile error C3892: 'e' : const인 변수에 할당할 수 없습니다.

    //*e = 5;       // Compile error C3892: 'e' : const인 변수에 할당할 수 없습니다.

 

    int const* const f = &aa;   // *f와 f에 대해서 상수로 보호

    //f = &aa;      // Compile error C3892: 'f' : const인 변수에 할당할 수 없습니다.

    //*f = 5;       // Compile error C3892: 'f' : const인 변수에 할당할 수 없습니다.

 

    printf( "b = %d\n", *b );

    printf( "c = %d\n", *c );

    printf( "d = %d\n", *d );

    printf( "e = %d\n", *e );

    printf( "f = %d\n", *f );

[출처] [c/c++] const 위치에 따른 상수 보호 범위|작성자 슈퍼베리코더



int nTmp1 = 0;

int nTmp2 = 0;


const int* pnConst1 = 0;

pnConst1 = &nTmp1; 

*pnConst1 = 0; //err


int* const pnConst2 = 0;

pnConst2 = &nTmp1; //err

*pnConst2 = 0;


const int* const pnConst3 = 0;


const int& rnConst1 = nTmp1;

rnConst1 = 0; //err

rnConst1 = nTmp2; //err


int& const rnConst2 = nTmp1; //const 무의미?

rnConst2 = 0;

rnConst2 = nTmp2;



const int& MyClass::foo(const int& a_rn) const;

마지막 const는 this를 다음과 같이 만듬.

const MyClass * const this;

즉, this->var = xxx; //err

블로그 이미지

란마12

,