Vector与数组的转化

可以重载*运算符

 

1  operator   float   * (){  return   & _x ;} ;
2  operator   const   float   * ()  const return   & _x ; } ;
3 

 

仿照D3D库中的例子,写出如下代码

代码
 1  #include  < iostream >
 2  using   namespace  std ;
 3 
 4  struct  Vector
 5  {
 6      Vector( float  x,  float  y,  float  z):_x(x), _y(y), _z(z){}
 7      Vector( float   * p):_x(p[ 0 ]), _y(p[ 1 ]), _z(p[ 2 ]){}
 8 
 9       operator   float   * (){  return   & _x ;} ;
10       operator   const   float   * ()  const return   & _x ; } ;
11 
12       float  _x ;
13       float  _y ;
14       float  _z ;
15  } ;
16 
17  void  OutputVector(Vector  & v)
18  {
19      cout  <<  v._x  <<   " "   <<  v._y  <<   " "   <<  v._z  <<  endl ;
20  }
21 
22  void  OutputArray( float   * p)
23  {
24      cout  <<  p[ 0 <<   " "   <<  p[ 1 <<   " "   <<  p[ 2 <<  endl ;
25  }
26 
27  int  main( void )
28  {
29       //  array -> vector
30       float  p[]  =  {  1 2 3 } ;
31      Vector v(p) ;
32      OutputVector(v) ;
33 
34       //  vector -> array
35      Vector v1( 2 3 4 ) ;
36       float   * p1  =  v1 ;
37      OutputArray(p1) ;
38 
39      system( " pause " ) ;
40       return   0  ;
41  }

 

 

你可能感兴趣的:(vector)