골치아픈 C++ const 용법 정리
int temp1 = 100; int temp2 = 200; ////////////////////////////////////////////////////////////////////////// // 1. 변수 ////////////////////////////////////////////////////////////////////////// const int i=100; // i = 200; // &i 는l-value 가아니므로대입자체가무효. ////////////////////////////////////////////////////////////////////////// // 2. 포인터형 ////////////////////////////////////////////////////////////////////////// // * 를기준으로왼쪽이냐오른쪽이냐에따라서다음과같다. // * 의왼쪽 const int * piConst = &temp1; // int const * piConst = &temp1; <- *의왼쪽으로위문장과동일. // *piConst // *piConst = 200; //
error // 하지만ipConst 는상수가아니므로주소는변경이가능하다. piConst = &temp2; // * 의오른쪽 int * const piConst2 =
&temp1; // piConst2 // piConst2 = &temp2; //
error // 하지만*piConst2 는상수가아니므로값은변경이가능하다. *piConst2 = 200; // 복합적 int const * const piConst3 =
&temp1; //const int * const const 와동일 // 완전상수다. ^^ // piConst3 = &temp2; // error // *piConst3 = 200; //
error ////////////////////////////////////////////////////////////////////////// // 3. 참조형 ////////////////////////////////////////////////////////////////////////// int const & refVal = temp1; // refVal = 200; error; // 역시&refVal 는l-value
가아니므로대입자체가무효 int & const refVal2 = temp1; // --> 이렇게사용하는것은VC 에서테스트해본결과아무효과가없어보인다. why? ////////////////////////////////////////////////////////////////////////// // 4. 함수 ////////////////////////////////////////////////////////////////////////// // class 의멤버함수에만const 선언가능. class A { private: int m_i; mutable int m_j; // const 로선언된멤버함수에서도변경이가능함. C++ 표준임. public: A() { m_i = 3; m_j = 5; } int GetValue() const { // m_i = 2; //
error. const 로선언된멤버함수는멤버변수변경불가. m_j = 4; return m_i; } } a; int k = a.GetValue(); ////////////////////////////////////////////////////////////////////////// // 5. 클래스 ////////////////////////////////////////////////////////////////////////// const class B { private: int m_i; public: int GetValue() { return m_i; } }; B b; const B & constB = b; // constB.GetValue(); //
error. GetValue 가const 가아니면사용할수없다. const A & constA = a; constA.GetValue(); // GetValue() 가const 이므로사용가능하다. ////////////////////////////////////////////////////////////////////////// // 6. const만차이가나는멤버함수들이오버로딩될수있다는사실 ////////////////////////////////////////////////////////////////////////// class C { int Add(int i, int j) { return (i+j); } int Add(int i, int j) const { return (i+j); } /* 아래는성립하지않음. int
Add(const int i, const int j) { return
(i+j); } */ }; |
책 : Effective C++
참고 사이트 : http://elky.tistory.com/99