C++オブジェクトモデルのオブジェクトを深く探求する


オブジェクト(一)
C言語では、「データ」と「データに対する処理(関数)」が別々に宣言されている.つまり、言語自体が「データと関数」の関連性をサポートしていない.たとえば、

   typedef struct point3d{
      float x;
      float y;
      float z;
   }point3d;

c++では、座標タイプと座標数をパラメータ化できます.

template<class type,int dim>
class Point
{
public:
  Point();
  Point(type coords[dim]){
     for(int index=0;index<dim;index++)
       _coords[index]=coords[index];  
  }
  type& operator[](int index){
     assert(index>=0 && index < dim);
     return _coords[index];
  }
  type operator[](int index) const{
     assert(index>=0 && index < dim);
     return _coords[index];
  }
  //------etc--------
  private:
    type _coords[dim];
};

inline
   template<class type,int dim>
ostream& operator<<(ostream &os,const Point<type,dim>& pt){
   os<<"(";
   for(int ix = 0;ix < dim-1;ix++)
     os<<pt[ix]<<", ";
  os<<pt[dim-1];
  os<<")";
}