본문 바로가기

C++/Data Type

Const

const 는 데이터 선언을 할 때 객체 또는 변수를 수정할 수 없음을 지정하는 수식어로, 해당 값이 상수임을 지정하고 코드 상에서 수정할 수 없도록 컴파일러에서 세팅하게 됩니다.


 

C++ 에서 정의된 const 값은 상수 식 대신 사용할 수 있습니다.

const int maxarray = 255;
char store_char[maxarray];  // allowed in C++; not allowed in C

 


 

멤버 함수를 const 로 선언하면 호출되는 객체 또는 변수를 수정하지 않는 "읽기 전용" 함수임을 지정합니다. 상수 멤버 함수는 비정적 데이터 멤버를 수정하거나 상수가 아닌 멤버 함수를 호출할 수 없습니다. 상수 멤버 함수를 선언하려면 인수 목록의 닫는 괄호 뒤에 const 를 선언해야 합니다.

 

즉, 상수 멤버 함수 안에서 호출되는 비정적 데이터는 수정이 불가능하다는 뜻입니다. ( 함수 반환값이랑은 상관 X )

class Date
{
public:
   Date( int mn, int dy, int yr );
   int getMonth() const;     // A read-only function
   void setMonth( int mn );   // A write function; can't be const
private:
   int month;
};

int Date::getMonth() const
{
   return month;        // Doesn't modify anything
}

void Date::setMonth( int mn )
{
   month = mn;          // Modifies data member
}

int main()
{
   Date MyDate( 7, 4, 1998 );
   const Date BirthDate( 1, 18, 1953 );
   
   MyDate.setMonth( 4 );    // Okay
   BirthDate.getMonth();    // Okay
   BirthDate.setMonth( 4 ); // C2662 Error
}

 

또한, const 로 선언된 객체const 멤버 함수만 호출이 가능하고, 객체 내 멤버 변수 수정은 불가능합니다. 

 


 

자료 출처

'C++ > Data Type' 카테고리의 다른 글

Pointer - vs - Reference  (0) 2024.01.16