const メンバ関数
本日、コンパイルを通している時に一瞬原因が分からなくてショックでした。
という事でアルツハイマー脳の為のメモ
class TestClass { public: TestClass():m_count(123){} int TestMethod1(void){ return m_count; } int TestMethod2(void)const{ return m_count; } private: int m_count; }
というクラスを定義したとします。これを以下のようにとある関数に渡してクラス内で定義した関数を呼び出します
void calleeMethod(const TestClass* testclass) { testclass->TestMethod1(); //コンパイルエラー testclass->TestMethod2(); //OK }
こうなります。TestClassにconstを付加し、メモリの書き換えを行わない宣言をしている為です。constメンバ関数以外は怒られてしまいます