【发布时间】:2015-08-29 10:22:31
【问题描述】:
我创建了自己的容器,该容器继承自向量。我想重新实现operator[] 以检查由#define 决定的边界。
举个例子,忽略模板参数,因为它们复杂且不相关
class MyArray : vector<double>
{
//...
virtual double& operator[](const size_type& index);
virtual const double& operator[](const size_type& index) const;
//...
}
double& MyArray::operator[](const size_type& index)
{
#ifdef DEBUG_ENABLED
return this->at(index);
#else
return (*this)[index];
#endif
}
但是,这不起作用,因为由于 operator[] 已重载,因此在 #else 处调用 operator[] 将变得递归。
我想根据我的#define 来检查边界,而不是根据我使用std::vector<>::at() 还是std::vector<>::operator[]。
我该如何解决这个问题?
编辑:因为它提供了很多使用 std::vector 作为成员而不是继承,我不得不提到这样做对我来说不是一个好的解决方案,因为我必须重新实现所有的成员函数标准::向量。这样做可不是那么愉快!
【问题讨论】:
-
std::vector的常见实现已经有了这个,所以你可以保持std::vector::operator[]不变。例如见here。 -
从
std::vector<double>开始实习而不是继承。 -
用
return vector<double>::at(index);代替return (*this)[index]; -
@πάνταῥεῖ 我会这样做,但我不喜欢那样,因为我必须重写 std::vector 的所有函数。
-
@TheQuantumPhysicist
I tried this now and it crashed my program too,为什么你的程序崩溃了?这不可能是递归问题,因为在注释中给您的调用调用了基类运算符 [ ]。见这里:coliru.stacked-crooked.com/a/2470e03aa0868f05 运行时错误不是由于堆栈溢出,而是由于索引超出范围。
标签: c++ class operator-overloading operators element