Share via


定数メンバー関数

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
}

参照

関連項目

定数 (C++)

定数値