2012-10-09 106 views
1

首先,我想说这是一个硬件任务,我只是有关于误差的问题,我现在面临C++载体模板操作符[]

我做了一个插入功能,增加了一个DATA_TYPE矢量模板到动态数组的末尾。这是我目前的。

// Insert the value at the specified index by moving the tail 
// when Size = Capacity the Vector has to be reallocated first 
// to accomate the new element 
void Insert(const DATA_TYPE& value, int index){ 

    // If the Capacity is not large enough then ... 
    // allocate large vector 
    if (Size >= Capacity){ 
     // 0. Let's boost the capacity 
     Capacity += CAPACITY_BOOST; 
     // 1. Allocate new larger vector 
     DATA_TYPE* newData = new DATA_TYPE[Capacity]; 

     // 2. Copy from old Data into the newData 
     for(int i=0; i< Size; i++) 
       newData[i] = Data[i]; 

     // 3. Delete the old Data 
     delete[] Data; 

     // 4. Replace old Data-pointer with the newData pointer 
     Data = newData; 
    } 

    // Move the tail 
    for(int i=index; i<Size;i++){ 
     Data[i+1] = Data[i]; 
    } 

    // Insert 
    Data[index] = value; 
    Size++; 

} 
DATA_TYPE& operator[] (int index) const{ 
    return *this[index]; 
} 

注意:使用私有变量:尺寸,容量,数据(存储动态数组) 我敢肯定,我已经正确地实现添加或功能的push_back。问题是,当我试图像cout < < a [1];“我得到一个错误。

while compiling class template member function 'int &Vector<DATA_TYPE>::operator [](int) const' 
     with 
     [ 
      DATA_TYPE=int 
     ] 
see reference to class template instantiation 'Vector<DATA_TYPE>' being compiled 
    with 
    [ 
      DATA_TYPE=int 
     ] 
error C2440: 'return' : cannot convert from 'const Vector<DATA_TYPE>' to 'int &' 
    with 
    [ 
     DATA_TYPE=int 
     ] 
+0

请坚持每个帖子有1个问题。 –

+0

对不起,感谢您的支持 – wzsun

回答

5

应该有2个版本的operator[]的:

const DATA_TYPE& operator[] (int index) const; 
DATA_TYPE& operator[] (int index); 

你有什么是两者的组合怪异。

你也应该返回

return Data[index]; 

返回(*this)[index];会导致无限递归调用(当然,不是无限的,你会得到在此之前,一个计算器)。

+0

+1你能解释无限递归部分吗?我想我完全不了解它。 – Mahesh

+0

@Mahesh肯定 - '(* this)[index]'相当于直接调用'operator [](index)',它会一次又一次地调用它自己。 –

+0

哦,狗屎我拖了,我之前,但当我打电话给我的功能显示通过cout我试图显示错误的索引(即[1]而不是[0]),并假定它必须改变*这[指数]。我觉得哑巴。不管怎么说,多谢拉。 – wzsun

1

operator[]函数被声明为恒定的,即,它不能改变在Vector对象任何东西。但是它返回一个引用,这意味着返回值可以修改。这两个相互矛盾。

这可以通过从函数结尾删除const或者不返回引用来解决。

+0

这不是什么OP代码错误。这可能不是一个好习惯,但它不是一个实际的错误(至少在正确实现'operator []'的时候)。 – Grizzly

2

有三个问题在这里:

  1. 运算符优先级。 *this[index]被解析为*(this[index]),而你的意思是(*this)[index]
  2. 您正在从const方法返回对您的数据的可变引用。
  3. operator[]的定义是循环的。在operator[]中返回(*this)[index]会导致无限递归。
+0

从技术上说,从该运算符返回可变引用没有任何问题(因为引用是由数据本身不是const的对象中的指针指向的数据)。不管这是否是好的做法可能会有争议,并取决于用例,但我不会说这是一个问题 – Grizzly

+0

@Grizzly:我不认为这是老师的期望。 –

+0

我真的不想推测这一点(根据我的经验,方法签名经常在这类练习的作业中给出)。这就是为什么我会说这是一个有用的建议,而不是那么少的读者解释它,因为你不能这样做。 – Grizzly