我正在实现一个向量,所以我希望它的行为像一个数组。这就是为什么我试图实现下标操作符,但我没有实现正确的行为。
其实现如下所示:
template <typename value_type>
class Vector{
private:
value_type ** vector ;
long size ;
long usedSize ;
public:
/.../
value_type & operator [] (long) ; // For writing.
const value_type & operator [] (long) const ; // For reading.
/.../
}
template<typename value_type>
value_type & Vector<value_type>::operator[] ( long index ) {
if ( index < 0 || index > usedSize )
return out_of_range () ;
else {
vector[index] = new value_type () ;
usedSize++ ;
return *(vector[index]) ;
}
}
template<typename value_type>
const value_type & Vector<value_type>::operator[] ( long index ) const {
if ( index < 0 || index > usedSize )
return out_of_range () ;
else { return (*vector[index]) ; }
}然后我用下面的代码测试对象的行为:
int main (void) {
Vector<int> * v = new Vector ( 10 ) ; // Creates a vector of 10 elements.
(*v)[0] = 3 ;
int a = (*v)[0] ;
cout << "a = " << a << endl ;
}我从行刑中得到了这样的结论:
$> a = 0 一些线程建议使用处理程序类重载赋值操作符,我想知道是否有任何方法可以避免使用处理程序对象来完成任务。
提前谢谢。
从阿根廷来的贡萨洛。
发布于 2013-06-02 07:52:21
你的假设是错误的
cout << "a =“<< (*v) << endl;
这个
向量常量value_type &
::operatorlong index常量
将会被使用。
事实上,这两次
矢量value_type::operator[](&V)
这样您就可以用新的值“替换”以前的值(同时也会泄漏内存)。
下面应该会有帮助
value_type & Vector<value_type>::operator[] ( long index ) {
if ( index < 0 || index > usedSize )
///out of bounds handling
else {
if(vector[index]== 0)
{
vector[index] = new value_type () ;
usedSize++ ;
}
return *(vector[index]) ;
}
}https://stackoverflow.com/questions/16878082
复制相似问题