// ( t6.C ) // コンストメンバ関数と変数 // #include // あまり使わない方がいいと思う! /* コンストメンバ関数の例 */ class Foo { int i ; public: Foo( int num ) { i = num ; } void set_i( int n ) { i = n ; } void show() const { cout << "katou\n" ; } // コンストメンバ関数指定 int get() const { return i ; } // コンストメンバ関数指定 const int& get2() const { return i ; } // コンストメンバ関数指定:参考 // void set1( int n ) const { i = n ; } クラス変数を設定したり、変更したりす // void set2() const { i = 2 ; } るメンバ関数は const 指定はできない。 } ; /* コンストメンバ変数の例 */ class Man { const int type ; // constがついていることに注意。変数の値の設定は public: // コンストラクタの Man():type(2) の形式のみで出 Man():type(2) {} // 来る。Man() { type = 2 ; } ではエラ−になる。 // void set() { type = 3 ; } 当然これもできない void show() { cout << "type = " << type << endl ; } } ; void main() { // 例題1 const Foo a(2) ; // a.set_i(3) ; クラス Foo を const 宣言しているので、これはできない。 cout << a.get() << endl ; cout << a.get2() << endl ; a.show() ; // 例題2 Foo b(20) ; b.show() ; b.set_i(30) ; // こっちはOK cout << b.get() << endl ; cout << b.get2() << endl ; } /* [参考] ちょっと機能としては複雑過ぎるように思う。一応C++では、こんなことも出来るよ という程度に考えた方がいいかも知れない。NIHクラス・ライブラリのソ−スを見る と、上記のような const の使われ方がよくされてはいるが。 */