Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/135.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/templates/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何定义可以拥有任意参数的模板类? 这个问题是在我阅读C++ Obj[1]对象模型时,第一章给出一个我不能理解的例子。_C++_Templates - Fatal编程技术网

如何定义可以拥有任意参数的模板类? 这个问题是在我阅读C++ Obj[1]对象模型时,第一章给出一个我不能理解的例子。

如何定义可以拥有任意参数的模板类? 这个问题是在我阅读C++ Obj[1]对象模型时,第一章给出一个我不能理解的例子。,c++,templates,C++,Templates,作者希望定义一个模板类,该类可以控制坐标的类型和数量 代码如下: 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&

作者希望定义一个模板类,该类可以控制坐标的类型和数量

代码如下:

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 < dim && index >= 0 );
      return _coords[ index ]; }
   type operator[]( int index ) const
      {   /* same as non-const instance */   }
   // ... 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 << " )";
}
模板
类点
{
公众:
点();
点(坐标类型[dim]){
对于(int index=0;index=0);
返回_坐标[索引];}
类型运算符[](整数索引)常量
{/*与非常量实例相同*/}
//……等等。。。
私人:
类型_坐标[dim];
};
内联
模板
奥斯特雷姆&
操作人员
index=0
是什么意思

如果
index
小于
dim
且大于或等于零,则其计算结果为
true

索引是类似于容器的向量吗

不,它是一个整数,用作数组的索引,
\u coords
。有效索引为0,1,…,
dim-1
,因此断言检查
索引是否在该范围内

他为什么要超越操作员

因此,您可以使用
[]
访问点的组件,就像它本身是一个数组一样

Point<float, 3> point; // A three-dimensional point
float x = point[0];    // The first component
float y = point[1];    // The second component
float z = point[2];    // The third component
float q = point[3];    // ERROR: there is no fourth component
Point点;//三维点
浮点x=点[0];//第一部分
浮动y=点[1];//第二部分
浮动z=点[2];//第三部分
浮点q=点[3];//错误:没有第四个组件

每一个调用重载操作符。最后一个将使断言失败;具体来说,
index
将是3,
dim
也将是3,因此
index
将是false。

它检查
index
是否小于
dim
且大于或等于
0
。运算符被重写,因此可以像使用数组一样访问元素。