这个问题是在看C++ Obj model,chapter 1的时候出现的,举个我看不懂的例子。
作者想定义一个类型和坐标个数都可以控制的模板类。
代码如下:
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 << " )";
}
什么是index < dim && index >= 0
方法? index是不是vector之类的容器?
他为什么要覆盖运算符(operator)?
最佳答案
what does
index < dim && index >= 0
means?
它的计算结果为 true
如果index
小于 dim
并且大于或等于零。
index is a container like vector?
不,它是一个用作数组索引的整数,_coords
.有效索引为 0、1、...、dim-1
, 所以断言检查 index
在那个范围内。
why did he override the operator?
所以你可以使用[]
访问点的组件,就好像它本身就是一个数组一样。
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
其中每一个都调用重载运算符。最后一个将使断言失败;具体来说,index
将是 3,dim
也将是 3,所以 index < dim
将是错误的。
关于c++ - 如何定义一个可以拥有任意参数的模板类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18761713/