【发布时间】:2017-01-20 19:54:05
【问题描述】:
我目前正在为 c++ 课程开发一个 Set-class,它是从 vector<T> 派生的。
在某一点上,我需要实现一个名为index() 的函数,它显然会返回(如果集合包含它)这些集合中对象的索引。
在编写整个课程时,我需要重载这些 index() 方法,这两个方法都是公共的。
所以这是我的两种方法:
第一个。有 3 个参数:
size_t index ( T const& x,size_t const& l, size_t const& r) const
{
if(l > size()||r>size())
throw("Menge::index(): index out of range.");
//cut the interval
size_t m = (l+r)/2;
// x was found
if( x == (*this)[m])
return m;
// x can't be found
if( l==m)
return NPOS;
//rekursive part
if( x < (*this)[m])
return index(l,m,x);
return index(m+1,r,x);
}
第二个有一个参数:
bool contains ( T const& elem ) const{
return index(elem, 0, size()-1)!=NPOS;
}
关键是我不想写这两种方法,如果可能的话,它可以合二为一。我考虑了index() 方法的默认值,所以我将方法头写成:
size_t index (T const& x, size_t const& l=0, size_t const& r=size()-1)const;
这给了我错误:
Elementfunction can't be called without a object
在考虑了这个错误之后,我尝试将其编辑为:
size_t index (T const& x, size_t const& l=0, size_t const& r=this->size()-1)const;
但这给了我错误:You're not allowed to call >>this<< in that context.
也许我错过了一些事情,但是如果你们中的任何人可以告诉我是否可以将方法作为默认参数调用,请告诉我。
【问题讨论】:
标签: c++ methods template-classes