constをデフォルトで使用し、変更を可能にしたい場合のみconstを外す。

  1. const char * const massage = "hello.";
  2.  
  3. void print(const Foo * const foo) {
  4. }
  5.  
  6. void print(const Foo& foo) {
  7. }
  8.  
  9. const std::vector<int>::const_iterator it = vec.begin();
  10.  
  11. class int_array {
  12. public :
  13. // ...
  14. const std::size_t& size() const {
  15. return data_.size();
  16. }
  17.  
  18. // constなオブジェクトのための[]演算子
  19. const int& operator[] (const std::size_t pos) const {
  20. return data_[pos];
  21. }
  22. // 非constなオブジェクトのための[]演算子
  23. int& operator[] (const std::size_t pos) {
  24. return
  25. const_cast<int&>( // []の戻り値からconstをキャストで外す
  26. static_cast<const int_array&>(*this)[pos] // constを*thisに付けてconstな[]を呼び出す
  27. );
  28. }
  29.  
  30. private :
  31. std::vector<int> data_;
  32. };
  33.  
最終更新:2010年03月01日 23:28