상수 멤버 함수

const 키워드로 멤버 함수를 선언하면 함수가 호출되는 개체를 수정하지 않는 "읽기 전용" 함수임을 나타냅니다.상수 멤버 함수는 비정적 데이터 멤버를 수정하거나 일정하지 않은 모든 멤버 함수를 호출할 수 없습니다.

상수 멤버 함수를 선언하려면, 인수 목록의 괄호를 닫은 후에 const 키워드를 배치합니다.const 키워드는 선언과 정의 모두에서 필요합니다.

예제

// constant_member_function.cpp
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 (C++)

상수 값