c++ const 용법

2009/01/20 10:57

1. 변수

const int i = 100;

//i 값변경불가

 

2. 포인터형 : 기본적으로 2가지형태가 있을 있음. 그외 여러형태가 가능
) 값은 변경 불가능하지만 주소는 변경가능한 형태

int temp = 100, temp2 = 200;

const int *ipConst = &temp; // *ipConst 값변경불가, ipConst(주소)값은변경가능

// int const *ipConst = &temp; // 이런형태로써도위와같은의미

 

// *ipConst = 300; // 불가능한형태

ipConst = &temp2; // 가능한형태

 

) 주소는 변경 불가능하지만 값은 변경가능한 형태

int temp = 100, temp2 = 200;

int * const iConstp = &temp; // *iConstp 값변경가능, iConstp(주소)값은변경불가

 

*iConstp = 300; // 가능한형태

//iConstp = &temp2; // 불가능한형태

 

주의 : const가 결합되는 위치가 값인지 주소인지에 유의

 

3. 참조형

) 직접적으로 값과 주소 모두 변경 불가능하지만 참조 원본을 통한 값변경은 가능한 경우

int temp3 = 100, temp5 = 200;

int const &ircVal = temp3;

 

//ircVal = 2000; // 컴파일에러발생(const 참조는값변경불가)

//ircVal = temp5; // 주소도변경불가

temp3 = 9000; // 참조원본은변경가능, 결과적으로ircVal의값도변하게됨

 

) 직접적으로 값과 주소 모두 변경 가능하지만 참조가 가르키는 값은 변화가 없는경우 (VS2008에서는 오래된 문법이라고 cosnt가 무시된다.)

int temp4 = 300, temp5 = 500;

int & const icrVal = temp4;

 

icrVal = 6000; // 값변경가능, 하지만값에변경이안됨

cout << " icrVal " << icrVal << endl; // 여전히 찍힘

icrVal = temp5; // 주소도변경가능역시값에변경이안됨

cout << " icrVal " << icrVal << endl; // 여전히 찍힘

 

4. 함수 : class의 멤버함수인 경우만 const 함수 사용가능. 해당 class의 멤버변수를 변경할수 없음.

class ConstTest

{

public:

           int m_iA;

 

           ConstTest()

           { m_iA = 1; }

           int const_func1( int &a_iA, int &a_iB) const

           {

                    int a = 1;

                      int b = 2;

                      int c = 0;

 

                      c = a + b;

                      a_iA += 100;

                      // m_iA += 100; // 에러발생. 멤버변수는변경불가

                      return m_iA;

            }

};

 

 

5. 클래스

const CMyConstClass CC;

// 내부멤버변수전체를변경불가능한클레스,(생성자함수만은예외)

// 모든내부멤버함수는기본적으로const 함수가되야만함.

// 내부함수의지역변수및인자로받은변수는변경가능.

 

 

출처 : http://elky.tistory.com/99

2009/01/20 10:57 2009/01/20 10:57
Posted by Junios

트랙백 보낼 주소 : http://junios.net/tc/trackback/222

<< PREV : [1] : ... [62] : [63] : [64] : [65] : [66] : [67] : [68] : [69] : [70] : ... [187] : NEXT >>

BLOG main image
Junios World by Junios

카테고리

전체 (187)
주저리 (60)
Tips (8)
적어놓기 (7)
Hacking (1)
Programming (110)
(1)

최근에 받은 트랙백

글 보관함

달력

«   2012/05   »
    1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31    
Total : 121509
Today : 21 Yesterday : 60